0% found this document useful (0 votes)
36 views74 pages

WT 3

efrgg

Uploaded by

adshi9153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views74 pages

WT 3

efrgg

Uploaded by

adshi9153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

JAVASCRIPT Notes

JAVASCRIPT
JavaScript is the scripting language of the Web.

JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and
much more.

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create
cookies, and much more.

JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as
Internet Explorer, Mozilla Firefox, and Opera.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in
the same category as C and C++.

What can a JavaScript Do ?

 JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and change the content
of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser

By – Prof Harshal V Patil Page 1


JAVASCRIPT Notes

 JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.

JavaScript Variables
Variables are "containers" for storing information.

JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to
display or change its value.

<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change the value,
and displays the value again.</p>

</body>
</html>

Output :
Welcome
XYZ

The script above declares a variable, assigns a value to it, displays the value, change the value, and
displays the value again.
By – Prof Harshal V Patil Page 2
JAVASCRIPT Notes

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Scorpio";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Scorpio.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.

These statements:

x=5;
carname="Scorpio";

have the same effect as:

var x=5;
var carname="Scorpio";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

By – Prof Harshal V Patil Page 3


JAVASCRIPT Notes

After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.

By – Prof Harshal V Patil Page 4


JAVASCRIPT Notes

DataTypes

 Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.
 Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string
literally; it doesn't process it. You'll use strings for text you want displayed or values you want
passed along.
 Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
 Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.

Data Types

TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is, nothing)

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

JavaScript Operators
The operator = is used to assign values.

The operator + is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;

By – Prof Harshal V Patil Page 5


JAVASCRIPT Notes

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

By – Prof Harshal V Patil Page 6


JAVASCRIPT Notes

After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"

Adding Strings and Numbers

Look at these examples:

x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

The rule is:

If you add a number and a string, the result will be a string.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

By – Prof Harshal V Patil Page 7


JAVASCRIPT Notes

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables
or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending
on the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

By – Prof Harshal V Patil Page 8


JAVASCRIPT Notes

Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value
"Dear President " else it will be assigned "Dear".

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if statement - use this statement if you want to execute some code only if a specified condition is
true
 if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
 if...else if....else statement - use this statement if you want to select one of many blocks of code to
be executed
 switch statement - use this statement if you want to select one of many blocks of code to be
executed

If Statement

You should use the if statement if you want to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();

By – Prof Harshal V Patil Page 9


JAVASCRIPT Notes

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();

if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
</script>

Note: When comparing variables you must always use two equals signs next to each other (==)!

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the
specified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition is not true, use
the if....else statement.

Syntax

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();

By – Prof Harshal V Patil Page 10


JAVASCRIPT Notes

var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines to execute.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else

By – Prof Harshal V Patil Page 11


JAVASCRIPT Notes

{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement

You should use the switch statement if you want to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically.

Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");

By – Prof Harshal V Patil Page 12


JAVASCRIPT Notes

break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing statement.

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{

By – Prof Harshal V Patil Page 13


JAVASCRIPT Notes

document.write("The number is " + i);


document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript While Loop

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

The while loop

The while loop is used when you want the loop to execute and continue executing while the specified
condition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>

By – Prof Harshal V Patil Page 14


JAVASCRIPT Notes

<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop

The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE,
and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the condition is
tested.

do
{
code to be executed
}
while (var<=endvalue);

Example

<html>
<body>
<script type="text/javascript">

By – Prof Harshal V Patil Page 15


JAVASCRIPT Notes

var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result

The number is 0

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.

JavaScript break and continue Statements

There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after the loop (if
any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
By – Prof Harshal V Patil Page 16
JAVASCRIPT Notes

</html>

Result

The number is 0
The number is 1
The number is 2

Continue

The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

By – Prof Harshal V Patil Page 17


JAVASCRIPT Notes

JavaScript Functions

A function (also known as a method) is a self-contained piece of code that performs a particular
"function". You can recognise a function by its format - it's a piece of descriptive text, followed by open
and close brackets.A function is a reusable code-block that will be executed by an event, or when the
function is called.

To keep the browser from executing a script when the page loads, you can put your script into a function.

A function contains code that will be executed by an event or by a call to that function.

You may call a function from anywhere within the page (or even from other pages if the function is
embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document. However, to
assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the
<head> section.

Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have
been executed as soon as the line was loaded. Now, the script is not executed before the user hits the
button. We have added an onClick event to the button that will execute the function displaymessage()
when the button is clicked.

By – Prof Harshal V Patil Page 18


JAVASCRIPT Notes

You will learn more about JavaScript events in the JS Events chapter.

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of
the function.

Note: A function with no parameters must include the parentheses () after the function name:

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in
lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the
exact same capitals as in the function name.

The return Statement

The return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b;
return x;
}

When you call the function above, you must pass along two parameters:

product=prod(2,3);

By – Prof Harshal V Patil Page 19


JAVASCRIPT Notes

The returned value from the prod() function is 6, and it will be stored in the variable called product.

The Lifetime of JavaScript Variables

When you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables. You can
have local variables with the same name in different functions, because each is recognized only by the
function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime of
these variables starts when they are declared, and ends when the page is closed.

What is an Event?

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript
programmers to control what happens when events occur.

Directly or indirectly, an Event is always the result of something a user does. For example, we've already
seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of
Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad
Event can be considered an indirect result of a user action.

Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the
distinction between them. An Event is merely something that happens - something that it is initiated by
an Event Handler (onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or "target elements," and we can
easily understand how a button which triggers a Click event is a target element for this event. Typically,
events are defined through the use of Event Handlers, which are bits of script that tell the browser what to
do when a particular event occurs at a particular target. These Event Handlers are commonly written as
attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"


onClick="event_handler_code">

The event_handler_code portion of this example is any valid JavaScript and it will be executed when the
specified event is triggered at this target element. This particular topic will be continued in Incorporating
JavaScripts into your HTML pages.

There are "three different ways" that Event Handlers can be used to trigger Events or Functions.

Method 1 (Link Events):

By – Prof Harshal V Patil Page 20


JAVASCRIPT Notes

Places an Event Handler as an attribute within an <A HREF= > tag, like this:

<A HREF="foo.html" onMouseOver="doSomething()"> ... </A>

You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link
respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the
</A> tags.

Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One
Link Event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is
called onMouseOver. This one gets sent when someone moves the cursor over the link.

You can use these events to affect what the user sees on a page. Here's an example of how to use link
events. Try it out, View Source, and we'll go over it.

<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link Events
</A>

The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the
quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because
semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an
entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.

Here are the three lines of interest:

1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>


2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');">
Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>

In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says,
"When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's
even a terminating semicolon at the end of the alert. Question: is this required? NO.

Let's go over each line:

1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser
reloads the page and goes to top of the page since it couldn't find the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when
you click on it. HREF="javascript: is the way to call a function when a link (hyperlink or an
HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default
behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert()
and also at the same time "deaden" the link.

By – Prof Harshal V Patil Page 21


JAVASCRIPT Notes

The next line is

<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">


Mouse over me!
</A>

This is just like the first line, but it uses an onMouseOver instead of an onClick.

Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to place an
onClick Event Handler inside a button type form element, like this:

<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>

While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event
Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function
defined in the header of the document or a single JavaScript command. Essentially, though, anything that
appears inside a command block (inside curly braces {}) can appear between the quotation marks.

For instance, if you have a form with a text field and want to call the function checkField() whenever the
value of the text field changes, you can define your text field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {


alert("Please enter a number greater than 5");
}">

To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);


confirm(‘Do you want to continue?’);">

The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler
code for multiple items in your document and, functions make your code easier to read and understand.

Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined involve the
onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of an
HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you set a flag

By – Prof Harshal V Patil Page 22


JAVASCRIPT Notes

within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely run,
with the knowledge that the document is fully loaded and all objects are defined. For example:

<SCRIPT>

var loaded = false;

function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}

</SCRIPT>

<BODY onLoad="loaded = true;">


-- OR --
<BODY onLoad="window.loaded = true;">

<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>

</BODY>

The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that
all images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins
(Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the
page is unloaded, which occurs when the browser is about to move on to a new page. Be aware that when
you are working with multiple frames, there is no guarantee of the order in which the onLoad Event
Handler is invoked for the various frames, except that the Event Handlers for the parent frame is invoked
after the Event Handlers of all its children frames -- This will be discussed in detail in Week 8.

Setting the bgColor Property

The first example allows the user to change the color by clicking buttons, while the second example
allows you to change colors by using drop down boxes.

Event Handlers

By – Prof Harshal V Patil Page 23


JAVASCRIPT Notes

EVENT DESCRIPTION
onAbort the user cancels loading of an image
input focus is removed from a form element (when the user clicks outside the field) or
onBlur
focus is removed from a window
onClick the user clicks on a link or form element
onChange the value of a form field is changed by the user
onError an error happens during loading of a document or image
onFocus input focus is given to a form element or a window
onLoad once a page is loaded, NOT while loading
onMouseOut the user moves the pointer off of a link or clickable area of an image map
onMouseOver the user moves the pointer over a hypertext link
onReset the user clears a form using the Reset button
onSelect the user selects a form element’s field
onSubmit a form is submitted (ie, when the users clicks on a submit button)
onUnload the user leaves a page

Note: Input focus refers to the act of clicking on or in a form element or field. This can be done by
clicking in a text field or by tabbing between text fields.

Which Event Handlers Can Be Used

OBJECT EVENT HANDLERS AVAILABLE


Button element onClick, onMouseOver
Checkbox onClick
Clickable ImageMap area onClick, onMouseOver, onMouseOut
Document onLoad, onUnload, onError
Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver, onMouseOut
Image onLoad, onError, onAbort

By – Prof Harshal V Patil Page 24


JAVASCRIPT Notes

Radio button onClick


Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus, onSelect
Text element onBlur, onChange, onFocus, onSelect
Window onLoad, onUnload, onBlur, onFocus

JavaScript Arrays

An array object is used to create a database-like structure within a script. Grouping data points
(array elements) together makes it easier to access and use the data in a script. There are methods
of accessing actual databases (which are beyond the scope of this series) but here we're talking
about small amounts of data.

An array can be viewed like a


column of data in a spreadsheet. The
name of the array would be the same
as the name of the column. Each
piece of data (element) in the array
is referred to by a number (index),
just like a row number in a column.

An array is an object. Earlier, I said


that an object is a thing, a collection
of properties (array elements, in this
case) grouped together.

You can name an array using the


same format as a variable, a function or an object. Remember our basic rules: The first
character cannot be a number, you cannot use a reserved word, and you cannot use spaces.
Also, be sure to remember that the name of the array object is capitalized, e.g. Array.

The JavaScript interpreter uses numbers to access the collection of elements (i.e. the data) in
an array. Each index number (as it is the number of the data in the array's index) refers to a
specific piece of data in the array, similar to an ID number. It's important to remember that
the index numbering of the data starts at "0." So, if you have 8 elements, the first element
will be numbered "0" and the last one will be "7."

Elements can be of any type: character string, integer, Boolean, or even another array. An
array can even have different types of elements within the same array. Each element in the

By – Prof Harshal V Patil Page 25


JAVASCRIPT Notes

array is accessed by placing its index number in brackets, i.e. myCar[4]. This would mean
that we are looking for data located in the array myCar which has an index of "4." Since the
numbering of an index starts at "0," this would actually be the fifth index. For instance, in the
following array,

var myCar = new Array("Chev","Ford","Buick","Lincoln","Truck");


alert(myCar[4])

the data point with an index of "4" would be Truck. In this example, the indexes are
numbered as follows: 0=Chev, 1=Ford, 2=Buick, 3=Lincoln, and 4=Truck. When creating
loops, it's much easier to refer to a number than to the actual data itself.

The Size of the Array

The size of an array is determined by either the actual number of elements it contains or by
actually specifying a given size. You don't need to specify the size of the array. Sometimes,
though, you may want to pre-set the size, e.g.:

var myCar = new Array(20);

That would pre-size the array with 20 elements. You might pre-size the array in order to set
aside the space in memory.

Multidimensional Arrays

This type of an array is similar to parallel arrays. In a multidimensional array, instead of


creating two or more arrays in tandem as we did with the parallel array, we create an array
with several levels or "dimensions." Remember our example of a spreadsheet with rows and
columns? This time, however, we have a couple more columns.

Multidimensional arrays can be created in different ways. Let's look at one of these method.
First, we create the main array, which is similar to what we did with previous arrays.
var emailList = new Array();

Next, we create arrays for elements of the main array:


By – Prof Harshal V Patil Page 26
JAVASCRIPT Notes

emailList[0] = new Array("President", "Paul Smith", "[email protected]");


emailList[1] = new Array("Vice President", "Laura Stevens", "[email protected]");
emailList[2] = new Array("General Manager", "Mary Larsen", "[email protected]");
emailList[3] = new Array("Sales Manager", "Bob Lark", "[email protected]");

In this script we created "sub arrays" or arrays from another level or "dimension." We used
the name of the main array and gave it an index number (e.g., emailList[0]). Then we created
a new instance of an array and gave it a value with three elements.

In order to access a single element, we need to use a double reference. For example, to get
the e-mail address for the Vice President in our example above, access the third element "[2]"
of the second element "[1]" of the array named emailList.

It would be written like this:

var vpEmail = emailList[1][2]


alert("The address is: "+ vpEmail)
1. We declared a variable, named it emailList, and initialized it with a
value of a new instance of an array.
2. Next, we created an array for each of the elements within the original
array. Each of the new arrays contained three elements.
3. Then we declared a variable named vpEmail and initialized it with the
value of the third element ([email protected]) of the second
element "[1]" of the array named emailList.

You could also retrieve the information using something like:

var title = emailList[1][0]


var email = emailList[1][2]
alert("The e-mail address for the " + title +" is: " + email)

By – Prof Harshal V Patil Page 27


JAVASCRIPT Notes

Array Properties
length

The length property returns the number of elements in an array. The format is
arrayName.length. The length property is particularly useful when using a loop to cycle
through an array. One example would be an array used to cycle banners:

var bannerImg = new Array();


bannerImg[0]="image-1.gif";
bannerImg[1]="image-2.gif";
bannerImg[2]="image-3.gif";

var newBanner = 0
var totalBan = bannerImg.length

function cycleBan() {
newBanner++
if (newBanner == totalBan) {
newBanner = 0
}
document.banner.src=bannerImg[newBanner]
setTimeout("cycleBan()", 3*1000)
}
window.onload=cycleBan;

This portion is then placed in the body where the banner is to be displayed:

&lt;img src="image-1.gif" name="banner">

Let's take a look and see what happened here:

By – Prof Harshal V Patil Page 28


JAVASCRIPT Notes

1. On the first line, we created a new instance of the array bannerImg, and gave it three data
elements. (Remember, we are only making a copy of the Array object here.)
2. Next, we created two variables: newBanner, which has a beginning value of zero; and
totalBan, which returns the length of the array (the total number of elements contained in the
array).
3. Then we created a function named cycleBan. This function will be used to create a loop to
cycle the images.
a. We set the newBanner variable to be increased each time the function cycles.
(Review: By placing the increment operator [" ++ "] after the variable [the
"operand"], the variable is incremented only after it returns its current value to the
script. For example, its beginning value is "0", so in the first cycle it will return a
value of "0" to the script and then its value will be increased by "1".)
b. When the value of the newBanner variable is equal to the variable totalBan (which is
the length of the array), it is then reset to "0". This allows the images to start the
cycle again, from the beginning.
c. The next statement uses the Document Object Method (DOM - we'll be taking a look
at that soon) to display the images on the Web page. Remember, we use the dot
operator to access the properties of an object. We also read the statement backwards,
i.e., "take the element from the array bannerImg, that is specified by the current
value of the variable newBanner, and place it in the src attribute located in the
element with the name attribute of banner, which is located in the document object."
d. We then used the setTimeout function to tell the script how long to display each
image. This is always measured in milliseconds so, in this case, the function
cycleBan is called every 3,000 milliseconds (i.e., every 3 seconds).
4. Finally, we used the window.onload statement to execute the function cycleBan as soon as
the document is loaded.

There are a total of five properties for the Array object. In addition to the length property
listed above, the others are:

1. constructor: Specifies the function that creates an object's prototype.


2. index: Only applies to JavaScript arrays created by a regular expression
match.
3. input: Only applies to JavaScript arrays created by a regular expression
match.
4. prototype: Used to add properties or methods.

By – Prof Harshal V Patil Page 29


JAVASCRIPT Notes

The other properties listed here are either more advanced or seldom used. For now, we'll
stick to the basics.

Javascript Object Hierarchy

Hierarchy Objects
Object Properties Methods Event Handlers
Window defaultStatus alert onLoad
frames blur onUnload
opener close onBlur
parent confirm onFocus
scroll focus
self open
status prompt
top clearTimeout
window setTimeout
History length back none
forward
go
Navigator appCodeName javaEnabled none
appName
appVersion
mimeTypes
plugins
userAgent
document alinkColor clear none (the onLoad and onUnload event handlers
anchors close belong to the Window object.
applets open
area write
bgColor writeln
cookie
fgColor
forms
images
lastModified
linkColor
links
location
referrer
title

By – Prof Harshal V Patil Page 30


JAVASCRIPT Notes

vlinkColor
image border none none
complete
height
hspace
lowsrc
name
src
vspace
width
form action submit onSubmit
elements reset onReset
encoding
FileUpload
method
name
target
text defaultValue focus onBlur
name blur onCharge
type select onFocus
value onSelect

Built-in Objects
Array length join none
reverse
sort xx
Date none getDate none
getDay
getHours
getMinutes
getMonth
getSeconds
getTime
getTimeZoneoffset
getYear
parse
prototype
setDate
setHours
setMinutes
setMonth
setSeconds
setTime

By – Prof Harshal V Patil Page 31


JAVASCRIPT Notes

setYear
toGMTString
toLocaleString
UTC
String length anchor Window
prototype big
blink
bold
charAt
fixed
fontColor
fontSize
indexOf
italics
lastIndexOf
link
small
split
strike
sub
substring
sup
toLowerCase
toUpperCase

JavaScript Array Object

The Array object is used to store multiple values in a single variable.

Create an Array

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as
many variables you require).

1:

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

By – Prof Harshal V Patil Page 32


JAVASCRIPT Notes

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be
numeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0.

The following code line:

document.write(myCars[0]);

will result in the following output:

Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

Opel

JavaScript Date Object

By – Prof Harshal V Patil Page 33


JAVASCRIPT Notes

Create a Date Object

The Date object is used to work with dates and times.

The following code create a Date object called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!

Set Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();


myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();


myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the
Date object itself!

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date();


myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

JavaScript Math Object


By – Prof Harshal V Patil Page 34
JAVASCRIPT Notes

Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an
object without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E,
PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log
of E.

You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also several
methods available.

The following example uses the round() method of the Math object to round a number to the nearest
integer:

document.write(Math.round(4.7));

The code above will result in the following output:

By – Prof Harshal V Patil Page 35


JAVASCRIPT Notes

The following example uses the random() method of the Math object to return a random number between
0 and 1:

document.write(Math.random());

The code above can result in the following output:

0.4218824567728053

The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:

document.write(Math.floor(Math.random()*11));

The code above can result in the following output:

JavaScript String Object

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";


document.write(txt.length);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to
uppercase letters:

var txt="Hello world!";


document.write(txt.toUpperCase());

The code above will result in the following output:

HELLO WORLD!

By – Prof Harshal V Patil Page 36


JAVASCRIPT Notes

Window Object

The Window object is the top level object in the JavaScript hierarchy.

The Window object represents a browser window.

A Window object is created automatically with every instance of a <body> or <frameset> tag.

IE: Internet Explorer, F: Firefox, O: Opera.

Window Object Collections


Collection Description IE F O
frames[] Returns all named frames in the window 4 1 9

Window Object Properties


Property Description IE F O
closed Returns whether or not a window has been closed 4 1 9
defaultStatus Sets or returns the default text in the statusbar of the window 4 No 9
document See Document object 4 1 9
history See History object 4 1 9
length Sets or returns the number of frames in the window 4 1 9
location See Location object 4 1 9
name Sets or returns the name of the window 4 1 9
opener Returns a reference to the window that created the window 4 1 9
outerHeight Sets or returns the outer height of a window No 1 No
outerWidth Sets or returns the outer width of a window No 1 No
pageXOffset Sets or returns the X position of the current page in relation to the No No No
upper left corner of a window's display area
pageYOffset Sets or returns the Y position of the current page in relation to the No No No
upper left corner of a window's display area
parent Returns the parent window 4 1 9
personalbar Sets whether or not the browser's personal bar (or directories bar)
should be visible
scrollbars Sets whether or not the scrollbars should be visible
self Returns a reference to the current window 4 1 9
status Sets the text in the statusbar of a window 4 No 9
statusbar Sets whether or not the browser's statusbar should be visible
toolbar Sets whether or not the browser's tool bar is visible or not (can only
be set before the window is opened and you must have
UniversalBrowserWrite privilege)
top Returns the topmost ancestor window 4 1 9

By – Prof Harshal V Patil Page 37


JAVASCRIPT Notes

Window Object Methods


Method Description IE F O
alert() Displays an alert box with a message and an OK button 4 1 9
blur() Removes focus from the current window 4 1 9
clearInterval() Cancels a timeout set with setInterval() 4 1 9
clearTimeout() Cancels a timeout set with setTimeout() 4 1 9
close() Closes the current window 4 1 9
confirm() Displays a dialog box with a message and an OK and a Cancel 4 1 9
button
createPopup() Creates a pop-up window 4 No No
focus() Sets focus to the current window 4 1 9
moveBy() Moves a window relative to its current position 4 1 9
moveTo() Moves a window to the specified position 4 1 9
open() Opens a new browser window 4 1 9
print() Prints the contents of the current window 5 1 9
prompt() Displays a dialog box that prompts the user for input 4 1 9
resizeBy() Resizes a window by the specified pixels 4 1 9
resizeTo() Resizes a window to the specified width and height 4 1.5 9
scrollBy() Scrolls the content by the specified number of pixels 4 1 9
scrollTo() Scrolls the content to the specified coordinates 4 1 9
setInterval() Evaluates an expression at specified intervals 4 1 9
setTimeout() Evaluates an expression after a specified number of milliseconds 4 1 9

Document Object

The Document object represents the entire HTML document and can be used to access all elements in a
page.

The Document object is part of the Window object and is accessed through the window.document
property.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Document Object Collections


Collection Description IE F O W3C
anchors[] Returns a reference to all Anchor objects in the 4 1 9 Yes
document
forms[] Returns a reference to all Form objects in the 4 1 9 Yes
document
images[] Returns a reference to all Image objects in the 4 1 9 Yes
document
links[] Returns a reference to all Area and Link objects in 4 1 9 Yes

By – Prof Harshal V Patil Page 38


JAVASCRIPT Notes

the document

Document Object Properties


Property Description IE F O W3C
body Gives direct access to the <body> element
cookie Sets or returns all cookies associated with the 4 1 9 Yes
current document
domain Returns the domain name for the current document 4 1 9 Yes
lastModified Returns the date and time a document was last 4 1 No No
modified
referrer Returns the URL of the document that loaded the 4 1 9 Yes
current document
title Returns the title of the current document 4 1 9 Yes
URL Returns the URL of the current document 4 1 9 Yes

Document Object Methods


Method Description IE F O W3C
close() Closes an output stream opened with the 4 1 9 Yes
document.open() method, and displays the
collected data
getElementById() Returns a reference to the first object with the 5 1 9 Yes
specified id
getElementsByName() Returns a collection of objects with the specified 5 1 9 Yes
name
getElementsByTagName() Returns a collection of objects with the specified 5 1 9 Yes
tagname
open() Opens a stream to collect the output from any 4 1 9 Yes
document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a 4 1 9 Yes
document
writeln() Identical to the write() method, with the addition 4 1 9 Yes
of writing a new line character after each
expression

History Object

The History object is actually a JavaScript object, not an HTML DOM object.

The History object is automatically created by the JavaScript runtime engine and consists of an array of
URLs. These URLs are the URLs the user has visited within a browser window.

The History object is part of the Window object and is accessed through the window.history property.

IE: Internet Explorer, F: Firefox, O: Opera.

By – Prof Harshal V Patil Page 39


JAVASCRIPT Notes

History Object Properties


Property Description IE F O
length Returns the number of elements in the history list 4 1 9

History Object Methods


Method Description IE F O
back() Loads the previous URL in the history list 4 1 9
forward() Loads the next URL in the history list 4 1 9
go() Loads a specific page in the history list 4 1 9

Form Object

The Form object represents an HTML form.

For each instance of a <form> tag in an HTML document, a Form object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Form Object Collections


Collection Description IE F O W3C
elements[] Returns an array containing each element in the form 5 1 9 Yes

Form Object Properties


Property Description IE F O W3C
acceptCharset Sets or returns a list of possible character-sets for the form data No No No Yes
action Sets or returns the action attribute of a form 5 1 9 Yes
enctype Sets or returns the MIME type used to encode the content of a 6 1 9 Yes
form
id Sets or returns the id of a form 5 1 9 Yes
length Returns the number of elements in a form 5 1 9 Yes
method Sets or returns the HTTP method for sending data to the server 5 1 9 Yes
name Sets or returns the name of a form 5 1 9 Yes
target Sets or returns where to open the action-URL in a form 5 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
dir Sets or returns the direction of text 5 1 9 Yes
lang Sets or returns the language code for an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

By – Prof Harshal V Patil Page 40


JAVASCRIPT Notes

Form Object Methods


Method Description IE F O W3C
reset() Resets the values of all elements in a form 5 1 9 Yes
submit() Submits a form 5 1 9 Yes

Image Object

The Image object represents an embedded image.

For each instance of an <img> tag in an HTML document, an Image object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Image Object Properties


Property Description IE F O W3C
align Sets or returns how to align an image according to the 5 1 9 Yes
surrounding text
alt Sets or returns an alternate text to be displayed, if a browser 5 1 9 Yes
cannot show an image
border Sets or returns the border around an image 4 1 9 Yes
complete Returns whether or not the browser has finished loading the 4 1 9 No
image
height Sets or returns the height of an image 4 1 9 Yes
hspace Sets or returns the white space on the left and right side of the 4 1 9 Yes
image
id Sets or returns the id of the image 4 1 9 Yes
isMap Returns whether or not an image is a server-side image map 5 1 9 Yes
longDesc Sets or returns a URL to a document containing a description 6 1 9 Yes
of the image
lowsrc Sets or returns a URL to a low-resolution version of an image 4 1 9 No
name Sets or returns the name of an image 4 1 9 Yes
src Sets or returns the URL of an image 4 1 9 Yes
useMap Sets or returns the value of the usemap attribute of an client- 5 1 9 Yes
side image map
vspace Sets or returns the white space on the top and bottom of the 4 1 9 Yes
image
width Sets or returns the width of an image 4 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

By – Prof Harshal V Patil Page 41


JAVASCRIPT Notes

Area Object

The Area object represents an area of an image-map (An image-map is an image with clickable regions).

For each instance of an <area> tag in an HTML document, an Area object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Area Object Properties


Property Description IE F O W3C
accessKey Sets or returns the keyboard key to access an area 5 1 No Yes
alt Sets or returns an alternate text to be displayed, if a browser 5 1 9 Yes
cannot show an area
coords Sets or returns the coordinates of a clickable area in an image- 5 1 9 Yes
map
hash Sets or returns the anchor part of the URL in an area 4 1 No No
host Sets or returns the hostname and port of the URL in an area 4 1 No No
href Sets or returns the URL of a link in an image-map 4 1 9 Yes
id Sets or returns the id of an area 4 1 9 Yes
noHref Sets or returns whether an area should be active or inactive 5 1 9 Yes
pathname Sets or returns the pathname of the URL in an area 4 1 9 No
protocol Sets or returns the protocol of the URL in an area 4 1 9 No
search Sets or returns the query string part of the URL in an area 4 1 9 No
shape Sets or returns the shape of an area in an image-map 5 1 9 Yes
tabIndex Sets or returns the tab order for an area 5 1 9 Yes
target Sets or returns where to open the link-URL in an area 4 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
dir Sets or returns the direction of text 5 1 9 Yes
lang Sets or returns the language code for an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

Navigator Object

The Navigator object is actually a JavaScript object, not an HTML DOM object.

The Navigator object is automatically created by the JavaScript runtime engine and contains information
about the client browser.

IE: Internet Explorer, F: Firefox, O: Opera.

By – Prof Harshal V Patil Page 42


JAVASCRIPT Notes

Navigator Object Collections


Collection Description IE F O
plugins[] Returns a reference to all embedded objects in the document 4 1 9

Navigator Object Properties


Property Description IE F O
appCodeName Returns the code name of the browser 4 1 9
appMinorVersion Returns the minor version of the browser 4 No No
appName Returns the name of the browser 4 1 9
appVersion Returns the platform and version of the browser 4 1 9
browserLanguage Returns the current browser language 4 No 9
cookieEnabled Returns a Boolean value that specifies whether cookies are 4 1 9
enabled in the browser
cpuClass Returns the CPU class of the browser's system 4 No No
onLine Returns a Boolean value that specifies whether the system is in 4 No No
offline mode
platform Returns the operating system platform 4 1 9
systemLanguage Returns the default language used by the OS 4 No No
userAgent Returns the value of the user-agent header sent by the client to 4 1 9
the server
userLanguage Returns the OS' natural language setting 4 No 9

Navigator Object Methods


Method Description IE F O
javaEnabled() Specifies whether or not the browser has Java enabled 4 1 9
taintEnabled() Specifies whether or not the browser has data tainting enabled 4 1 9

ZIP CODE VALIDATION

<!-- TWO STEPS TO INSTALL ZIP CODE VALIDATION:

1. Copy the coding into the HEAD of your HTML document

2. Add the last code into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Original: Brian Swalwell -->

By – Prof Harshal V Patil Page 43


JAVASCRIPT Notes

<!-- This script and many more are available free online at -->

<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin

function validateZIP(field) {

var valid = "0123456789-";

var hyphencount = 0;

if (field.length!=5 && field.length!=10) {

alert("Please enter your 5 digit or 5 digit+4 zip code.");

return false;

for (var i=0; i < field.length; i++) {

temp = "" + field.substring(i, i+1);

if (temp == "-") hyphencount++;

if (valid.indexOf(temp) == "-1") {

alert("Invalid characters in your zip code. Please try again.");

return false;

if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {

alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-
6789'. Please try again.");

return false;

return true;

By – Prof Harshal V Patil Page 44


JAVASCRIPT Notes

// End -->

</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<center>

<form name=zip onSubmit="return validateZIP(this.zip.value)">

Zip: <input type=text size=30 name=zip>

<input type=submit value="Submit">

</form>

</center>

<p><center>

<font face="arial, helvetica" size="-2">Free JavaScripts provided<br>

by <a href="http://javascriptsource.com">The JavaScript Source</a></font>

</center><p>

By – Prof Harshal V Patil Page 45


Java Networking
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources.
Java socket programming provides facility to share data between different
computing devices.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication
between the sender and receiver. TCP is used along with the Internet
Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol
service by allowing packet of data to be transferred along two or more
nodes
Java Networking Terminology
The widely used Java networking terminologies are given below:
Advertisement
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1
. It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For
example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between
two applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with
unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it
is reliable but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver.
So it is not reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
java.net package
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e.
networking identifiers, Sockets i.e. bidirectional data communication
mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal
Resource Identifier, URLs i.e. Universal Resource Locator, and
Connections i.e. connections to the resource pointed by URLs.

Java Socket Programming


Java Socket programming is used for communication between the applications
running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and
prints it. Here, two classes are being used: Socket and ServerSocket. The Socket
class is used to communicate client and server. Through this class, we can read
and write message. The ServerSocket class is used at server-side. The accept()
method of ServerSocket class blocks the console until the client is connected.
After the successful connection of client, it returns the instance of Socket at
server-side.

Socket class
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Important methods
Method Description

returns the InputStream attached with


1) public InputStream getInputStream()
this socket.

2) public OutputStream returns the OutputStream attached with


getOutputStream() this socket.

3) public synchronized void close() closes this socket


ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used
to establish communication with the clients.
Important methods
Method Description

returns the socket and establish a


1) public Socket accept()
connection between server and client.

2) public synchronized void close() closes the server socket.


Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of
ServerSocket class. Here, we are using 6666 port number for the
communication between the client and server. You may also choose any other
port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
2. Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:
Advertisement
To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port
number. Here, we are using "localhost" because our server is running on same
system.
1. Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and
server receives and prints it.
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10.System.out.println("message= "+str);
11.ss.close();
12.}catch(Exception e){System.out.println(e);}
13.}
14.}
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());

8. dout.writeUTF("Hello Server");
9. dout.flush();
10.dout.close();
11.s.close();
12.}catch(Exception e){System.out.println(e);}
13.}
14.}
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and
print the text. Then server will write to the client and client will receive and
print the text. The step goes on.
Advertisement
File: MyServer.java
1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());

9. BufferedReader br=new BufferedReader(new InputStreamReader(Syste


m.in));
10.
11.String str="",str2="";
12.while(!str.equals("stop")){
13.str=din.readUTF();
14.System.out.println("client says: "+str);
15.str2=br.readLine();
16.dout.writeUTF(str2);
17.dout.flush();
18.}
19.din.close();
20.s.close();
21.ss.close();
22.}}
File: MyClient.java
1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(Syste
m.in));
9.
10.String str="",str2="";
11.while(!str.equals("stop")){
12.str=br.readLine();
13.dout.writeUTF(str);
14.dout.flush();
15.str2=din.readUTF();
16.System.out.println("Server says: "+str2);
17.}
18.
19.dout.close();
20.s.close();
21.}}
Java InetAddress class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of
InetAddress represents the IP address with its corresponding host name. There are two types
of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface whereas
Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host
name resolutions.
IP Address
o An IP address helps to identify a specific resource on the network using a numerical
representation.
o Most networks combine IP with TCP (Transmission Control Protocol). It builds a
virtual bridge among the destination and the source.
There are two versions of IP address:
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in
the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network
using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is
more than 4 million addresses.
Features of IPv4:
o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with the class
based addressing scheme.
o It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet
addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address
space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also
identified with a name IPng (Internet Protocol next generation).
Features of IPv6:
o It has a stateful and stateless both configurations.
o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.
TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a network via
internet.
o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.
o The two main protocols used in this communication model are:
o TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of
packets at sender end as well as receiver end.
o IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct
and the message is forwarded correctly or not.
Java InetAddress Class Methods

Method Description

public static InetAddress getByName(String It returns the instance of InetAddress


host) throws UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() throws It returns the instance of InetAdddress


UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

Example of Java InetAddress Class


Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com
website.
InetDemo.java
Advertisement
1. import java.io.*;
2. import java.net.*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=InetAddress.getByName("www.javatpoint.com");
7.
8. System.out.println("Host Name: "+ip.getHostName());
9. System.out.println("IP Address: "+ip.getHostAddress());
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
Output:
Program to demonstrate methods of InetAddress class
InetDemo2.java
1. import java.net.Inet4Address;
2. import java.util.Arrays;
3. import java.net.InetAddress;
4. public class InetDemo2
5. {
6. public static void main(String[] arg) throws Exception
7. {
8. InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
9. InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
10. byte addr[]={72, 3, 2, 12};
11. System.out.println("ip : "+ip);
12. System.out.print("\nip1 : "+ip1);
13. InetAddress ip2 = InetAddress.getByAddress(addr);
14. System.out.print("\nip2 : "+ip2);
15. System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
16. System.out.print("\nHost Address : " +ip.getHostAddress());
17. System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
18. System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
19. System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
20. System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
21. System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
22. System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
23. System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
24. System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
25. System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
26. System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
27. System.out.print("\nhashCode : " +ip.hashCode());
28. System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
29. }
30. }
Output:

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator.
It points to a resource on the World Wide Web. For example:
1. https://www.javatpoint.com/java-tutorial

A URL contains many information:


1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Constructors of Java URL class


URL(String spec)
Creates an instance of a URL from the String representation.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a
given context.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are
given below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.


public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

it returns the string representation of the


public String toString()
URL.

public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.

it returns the instance of URLConnection i.e.


public URLConnection openConnection()
associated with this URL.

public boolean equals(Object obj) it compares the URL with the given object.

public Object getContent() it returns the content of the URL.

public String getRef() it returns the anchor or reference of the URL.

public URI toURI() it returns a URI of the URL.

Example of Java URL class


1. //URLDemo.java
2. import java.net.*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7.
8. System.out.println("Protocol: "+url.getProtocol());
9. System.out.println("Host Name: "+url.getHost());
10. System.out.println("Port Number: "+url.getPort());
11. System.out.println("File Name: "+url.getFile());
12.
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

Let us see another example URL class in Java.


1. //URLDemo.java
2. import java.net.*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&s
ourceid=chrome&ie=UTF-8");
7.
8. System.out.println("Protocol: "+url.getProtocol());
9. System.out.println("Host Name: "+url.getHost());
10. System.out.println("Port Number: "+url.getPort());
11. System.out.println("Default Port Number: "+url.getDefaultPort());
12. System.out.println("Query String: "+url.getQuery());
13. System.out.println("Path: "+url.getPath());
14. System.out.println("File: "+url.getFile());
15.
16. }catch(Exception e){System.out.println(e);}
17. }
18. }
Output:
Protocol: https
Host Name: www.google.com
Port Number: -1
Default Port Number: 443
Query String: q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8

Java URLConnection Class


The Java URLConnection class represents a communication link between the URL and the
application. It can be used to read and write data to the specified resource referred by the
URL.
What is the URL?
o URL is an abbreviation for Uniform Resource Locator. An URL is a form of string
that helps to find a resource on the World Wide Web (WWW).
o URL has two components:
1. The protocol required to access the resource.
2. The location of the resource.
Features of URLConnection class
1. URLConnection is an abstract class. The two subclasses HttpURLConnection and
JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any
resource referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object,
we can use it to read or write or get further information like content length, etc.
Constructors

Constructor Description

It constructs a URL connection to the specified


1) protected URLConnection(URL url)
URL.
URLConnection Class Methods

Method Description

It adds a general request property specified


void addRequestProperty(String key, String value)
by a key-value pair

It opens a communications link to the


void connect() resource referenced by this URL, if such a
connection has not already been established.

It returns the value of the


boolean getAllowUserInteraction()
allowUserInteraction field for the object.

int getConnectionTimeout() It returns setting for connect timeout.

It retrieves the contents of the URL


Object getContent()
connection.

It retrieves the contents of the URL


Object getContent(Class[] classes)
connection.

It returns the value of the content-encoding


String getContentEncoding()
header field.

It returns the value of the content-length


int getContentLength()
header field.

It returns the value of the content-length


long getContentLengthLong()
header field as long.

String getContentType() It returns the value of the date header field.

long getDate() It returns the value of the date header field.

It returns the default value of the


static boolean getDefaultAllowUserInteraction()
allowUserInteraction field.

It returns the default value of an


boolean getDefaultUseCaches()
URLConnetion's useCaches flag.
It returns the value of the URLConnection's
boolean getDoInput()
doInput flag.

It returns the value of the URLConnection's


boolean getDoInput()
doOutput flag.

It returns the value of the expires header


long getExpiration()
files.

static FileNameMap getFilenameMap() It loads the filename map from a data file.

String getHeaderField(int n) It returns the value of nth header field

It returns the value of the named header


String getHeaderField(String name)
field.

long getHeaderFieldDate(String name, long It returns the value of the named field parsed
Default) as a number.

It returns the value of the named field parsed


int getHeaderFieldInt(String name, int Default)
as a number.

String getHeaderFieldKey(int n) It returns the key for the nth header field.

long getHeaderFieldLong(String name, long It returns the value of the named field parsed
Default) as a number.

It returns the unmodifiable Map of the


Map<String, List<String>> getHeaderFields()
header field.

It returns the value of the object's


long getIfModifiedSince()
ifModifiedSince field.

It returns an input stream that reads from the


InputStream getInputStream()
open condition.

It returns the value of the last-modified


long getLastModified()
header field.
It returns an output stream that writes to the
OutputStream getOutputStream()
connection.

It returns a permission object representing


Permission getPermission() the permission necessary to make the
connection represented by the object.

int getReadTimeout() It returns setting for read timeout.

Map<String, List<String>> It returns the value of the named general


getRequestProperties() request property for the connection.

It returns the value of the URLConnection's


URL getURL()
URL field.

It returns the value of the URLConnection's


boolean getUseCaches()
useCaches field.

It tries to determine the content type of an


Static String guessContentTypeFromName(String
object, based on the
fname)
specified file component of a URL.

It tries to determine the type of an input


static String
stream based on the characters at the
guessContentTypeFromStream(InputStream is)
beginning of the input stream.

void setAllowUserInteraction(boolean It sets the value of the allowUserInteraction


allowuserinteraction) field of this URLConnection.

static void
It sets the ContentHandlerFactory of an
setContentHandlerFactory(ContentHandlerFactory
application.
fac)

It sets the default value of the


static void
allowUserInteraction field for all future
setDefaultAllowUserInteraction(boolean
URLConnection objects to the specified
defaultallowuserinteraction)
value.

void steDafaultUseCaches(boolean It sets the default value of the useCaches


defaultusecaches) field to the specified value.
It sets the value of the doInput field for this
void setDoInput(boolean doinput)
URLConnection to the specified value.

It sets the value of the doOutput field for the


void setDoOutput(boolean dooutput)
URLConnection to the specified value.

How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection class.
Syntax:
1. public URLConnection openConnection()throws IOException{}
Displaying Source Code of a Webpage by URLConnecton Class
The URLConnection class provides many methods. We can display all the data of a webpage
by using the getInputStream() method. It returns all the data of the specified URL in the
stream that can be read and displayed.
Advertisement
Example of Java URLConnection Class
1. import java.io.*;
2. import java.net.*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7. URLConnection urlcon=url.openConnection();
8. InputStream stream=urlcon.getInputStream();
9. int i;
10. while((i=stream.read())!=-1){
11. System.out.print((char)i);
12. }
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Java HttpURLConnection class
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
By the help of HttpURLConnection class, you can retrieve information of any HTTP URL
such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.

HttpURLConnection Class Constructor

Constructor Description

It constructs the instance of


protected HttpURLConnection(URL u)
HttpURLConnection class.

Java HttpURLConnection Methods

Method Description

It shows that other requests from the server are


void disconnect()
unlikely in the near future.

It returns the error stream if the connection


InputStream getErrorStream()
failed but the server sent useful data.

It returns a boolean value to check whether or


Static boolean getFollowRedirects() not HTTP redirects should be automatically
followed.

String getHeaderField(int n) It returns the value of nth header file.

long getHeaderFieldDate(String name, long It returns the value of the named field parsed as
Default) a date.

String getHeaderFieldKey(int n) It returns the key for the nth header file.

It returns the value of HttpURLConnection's


boolean getInstanceFollowRedirects()
instance FollowRedirects field.
It returns the SocketPermission object
Permission getPermission() representing the permission to connect to the
destination host and port.

String getRequestMethod() It gets the request method.

It gets the response code from an HTTP


int getResponseCode()
response message.

It gets the response message sent along with the


String getResponseMessage()
response code from a server.

The method is used to enable streaming of a


HTTP request body without internal buffering,
void setChunkedStreamingMode(int chunklen)
when the content length is not known in
advance.

The method is used to enable streaming of a


void setFixedLengthStreamingMode(int
HTTP request body without internal buffering,
contentlength)
when the content length is known in advance.

The method is used to enable streaming of a


void setFixedLengthStreamingMode(long HTTP request body without internal buffering,
contentlength) when the content length is not known in
advance.

It sets whether HTTP redirects (requests with


static void setFollowRedirects(boolean set) response code) should be automatically
followed by HttpURLConnection class.

It sets whether HTTP redirects (requests with


void setInstanceFollowRedirects(boolean response code) should be automatically
followRedirects) followed by instance of HttpURLConnection
class.

Sets the method for the URL request, one of:


GET POST HEAD OPTIONS PUT DELETE
void setRequestMethod(String method)
TRACE are legal, subject to protocol
restrictions.
It shows if the connection is going through a
abstract boolean usingProxy()
proxy.

How to get the object of HttpURLConnection class


The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
1. public URLConnection openConnection()throws IOException{}
You can typecast it to HttpURLConnection type as given below.
1. URL url=new URL("http://www.javatpoint.com/java-tutorial");
2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();
Java HttpURLConnection Example
1. import java.io.*;
2. import java.net.*;
3. public class HttpURLConnectionDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7. HttpURLConnection huc=(HttpURLConnection)url.openConnection();
8. for(int i=1;i<=8;i++){
9. System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
10. }
11. huc.disconnect();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Test it Now
Output:
Date = Thu, 22 Jul 2021 18:08:17 GMT
Server = Apache
Location = https://www.javatpoint.com/java-tutorial
Cache-Control = max-age=2592000
Expires = Sat, 21 Aug 2021 18:08:17 GMT
Content-Length = 248
Keep-Alive =timeout=5, max=1500
Connection = Keep-Alive
Types of Sockets in Java

Socket is the concept at the core of Java's networking support. The socket paradigm was part of the 4.2BSD
Berkeley UNIX release in the early 1980s. For this reason, the name Berkeley socket is used. Socket is the
basis of a modern network because the socket allows one computer to run multiple clients at the same time,
as well as to provide multiple types of information. And it is achieved by using a port, which is a numbered
socket on a specific machine. Now, until the client connects to the server, the server process is said to "listen"
to a port. The server is allowed to host multiple clients connected to the same port number, although each
session is different. In order to control multi-client connections, the server process must be multi-threaded
or have other ways of multiplexing the simultaneous I/O.

Socket connection occurs via protocol. Internet Protocol (IP) is a low-level routing protocol that separates
data into small packets and sends it to an address across the network. But in this there is no guarantee of the
delivery of the packets to its destination. For a reliable transmit of data, there is another higher-level protocol
known as Transmission Control Protocol (TCP) which manages to string together these packets robustly,
sorting and retransmitting them as necessary. A third protocol, known as User Datagram Protocol (UDP), can
be used directly to support fast, offline, unreliable packet transfers.

After establishing the connection, a higher-level protocol ensures, which is dependent on which port you are
using. TCP/IP holds the lower 1,024 ports for certain protocols. And if you have spent enough time surfing the
Internet, many of these will seem very familiar to you. Port number 23 is for Telnet; 21 for FTP; 43 is for
whois;25 is for e-mail; 80 is for HTTP; 79 is for finger; 119 is for netnews - and so on. How the client should
interact with the port is determined by each protocol.

Types of Sockets in Java

Java supports the following three types of sockets:

o Stream Sockets

o Datagram Sockets

o Raw Sockets

Stream Sockets

Stream Sockets allow processes to communicate using TCP. Stream sockets provide a two-way, reliable,
ordered, non-replicated stream of data with no record boundaries. It is connection-oriented socket. Once a
connection is established, data can be read and written from these sockets as streams of bytes. The socket
type is SOCK_STREAM.
Stream sockets are used when we need a reliable connection to send and receive multiple messages
between two network programs. Stream sockets rely on TCP to ensure that messages arrive at their
destinations without errors. In practice, IP packets are likely to be lost on the network or arrive erroneous.
Either way, the receiving TCP connects to the sending TCP and resends that IP packet. This establishes a
reliable connection between the two stream sockets.

Stream sockets play the necessary role in the client/server programs. The client program (that is, a network-
aware program that requires access to some service) attempts to create a stream socket object with the IP
address of a server program's host and the port number of the server program (that is, a network-aware
program that provides a service to client programs). The client program's stream socket initialization code
passes the IP address and port number to the client host's network-management software.

This software passes the IP address and port number (via IP) to the server host through NIC. The network-
management software at the server host is attempted to read the data (via IP) from the NIC and try to verify
that the server program is listening for connection requests via its stream socket on the specified port. The
network-management software on the host server responds to the client host's network-management
software with a positive acknowledgment if the server program is listening. In response to the client
program's stream socket initialization code, a port number is established for the client program, the port
number is passed (via the client and server hosts' network-management software) to the server program's
stream socket (which uses that number to identify the client program to which messages will be sent), and
initialization of the stream socket object is completed.

If the server program is not listening on the port, the server host network management software responds to
the client host network management software with a negative acknowledgment. In response, the client
program's stream socket initialization code throws an exception object and does not establish a
communication channel (it does not create a stream socket object).

TCP/IP Client Sockets

TCP/IP sockets are used to implement reliable two-way, persistent, point-to-point streaming connections
between hosts on the Internet. The Java I/O system can use sockets to connect to other programs on the
local system or on other systems on the Internet. It is important to note that the applet establishes a reverse
socket connection to the host on which the applet is loaded. This restriction exists because it is dangerous for
applets loaded through a firewall to access arbitrary systems. There are two types of TCP sockets in Java.

Advertisement

One for the server and one for the client. The ServerSocket class is designed as a "listener", waiting for a
client to connect before doing anything. So ServerSocket is for servers. The Socket class is for clients. It is
designed to connect to a server socket and initiate a protocol exchange. This is because client sockets are
most commonly used in Java applications. Creating a Socket object implicitly establishes a connection
between the client and server. There is no method or constructor that explicitly exposes details about setting
up this connection.

Here are the two constructors used to create a client socket:

1. Socket(String hostName, int port) throws UnknownHostException, IOException: Creates a socket


connected to the specified host and port.

2. Socket(InetAddress ipAddress, int port) throws IOException: Creates a socket using a pre-existing
InetAddress object and a port.
Socket defines multiple instance methods. For example, a Socket can always check for associated address and
port information using the following methods:

1. InetAddress getInetAddress( ): It returns the InetAddress associated with the Socket object. It
returns null if the socket is not connected.

2. int getPort( ): It returns the remote port to which the invoking Socket object is connected. It returns
0 if the socket is not connected.

3. int getLocalPort( ): Returns the local port to which the invoking Socket object is bound. It returns -1 if
the socket is not bound.

4. InputStream getInputStream( ) throws IOException: Returns the InputStream associated with the
invoking socket.

5. OutputStream getOutputStream( ) throws IOException: Returns the OutputStream associated with


the invoking socket.

6. connect( ): Allows you to specify a new connection

7. isConnected( ): Returns true if the socket is connected to a server

8. isBound( ): Returns true if the socket is bound to an address

9. isClosed( ): Returns true if the socket is closed.

The following program provides a simple socket example. Opens a connection to a "whois" port (port 43) of
the InterNIC server, sends command-line argument to the socket, and prints the returned data. The InterNIC
will try find the argument by the registered Internet domain name, and then send back the IP address and
contact information for that site.

Datagram Sockets

Datagram sockets allow processes to use UDP for communication. Datagram sockets support bidirectional
message flow. It is a connection-less socket. A process on a datagram socket may receive messages in a
different order than the order in which they are sent, and may receive duplicate messages. The record
boundaries of the data are preserved. The socket type is SOCK_DGRAM.

TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable,
reliable stream of packet data. This is not without its cost, however. TCP incorporates many state-of-the-art
algorithms to deal with congestion control on crowded networks, as well as pessimistic expectations about
packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative.

Datagrams are vast amounts of information that is transmitted between machines. Once the datagram has
been released for its intended purpose, there is no guarantee that it will arrive or even that someone will be
there to catch it. Similarly, when the datagram is received, there is no guarantee that it hasn't been damaged
in transit or that anyone who sent it is still there to get a response.

Advertisement

Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object is
the data container, while the DatagramSocket is the mechanism used to send or receive the
DatagramPackets.

DatagramSocket
DatagramSocket defines four public constructors. They are shown here:

o DatagramSocket( ) throws SocketException- Creates a Datagram socket bound to any unused port
on the local computer.

o DatagramSocket(int port) throws SocketException- Creates a DatagramSocket bound to the port


specified by the port.

o DatagramSocket(int port, InetAddress ipAddress) throws SocketException- Constructs a


DatagramSocket bound to the specified port and InetAddress.

o DatagramSocket(SocketAddress address) throws SocketException- Constructs a DatagramSocket


bound to the specified SocketAddress. SocketAddress is an abstract class that is implemented by the
concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number.
All can throw a SocketException if an error occurs while creating the socket.

Advertisement

DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are
shown here:

o void send(DatagramPacket packet) throws IOException- Sends the packet to the port specified by
the packet.

o void receive(DatagramPacket packet) throws IOException- Waits for a packet to be received from
the port specified by the packet and returns the result.

Other methods give you access to various attributes associated with a DatagramSocket.

Here is a sampling:

o InetAddress getInetAddress( ): If the socket is connected, then the address is returned. Otherwise,
null is returned.

o int getLocalPort( ): It returns the number of the local port.

o int getPort( ): Returns the number of the port to which the socket is connected. It returns -1 if the
socket is not connected to a port.

o boolean isBound( ): Returns true if the socket is bound to an address. Returns false otherwise.

o boolean isConnected( ): Returns true if the socket is connected to a server. Returns false otherwise.

o void setSoTimeout(int millis) throws SocketException: Sets the time-out period to the number of
milliseconds passed in millis.

DatagramPacket

DatagramPacket defines several constructors. Four are shown here:

o DatagramPacket(byte data[ ], int size) : Specifies a buffer that will receive data and the size of a
packet. It is used for receiving data over a DatagramSocket.

o DatagramPacket(byte data[ ], int offset, int size) : Allows us to specify an offset into the buffer at
which data will be stored.
o DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : Specifies a target address
and port, which are used by a DatagramSocket to determine where the data in the packet will be
sent.

o DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : Transmits
packets beginning at the specified offset into the data.

DatagramPacket defines several methods, including those shown here, that give access to the address and
port number of a packet, as well as the raw data and its length. In general, the get methods are used on
packets that are received, and the set methods are used on

packets that will be sent.

o InetAddress getAddress( ) : Returns the address of the source (for datagrams being received) or
destination (for datagrams being sent).

o byte[ ] getData( ) : Returns the byte array of data contained in the datagram. Mostly used to retrieve
data from the datagram after it has been received.

o int getLength( ) : Returns the length of the valid data contained in the byte array that would be
returned from the getData( ) method. This may not equal the length of the whole byte array.

o int getOffset( ) : Returns the starting index of the data.

o int getPort( ) : Returns the port number.

o void setAddress(InetAddress ipAddress) : Sets the address to which a packet will be sent. The
address is specified by ipAddress.

o void setData(byte[ ] data) : Sets the data to data, the offset to zero, and the length to the number of
bytes in data.

o void setData(byte[ ] data, int idx, int size) : Sets the data to data, the offset to idx, and the length to
size.

o void setLength(int size) : Sets the length of the packet to size.

o void setPort(int port) : Sets the port to port.

Example of Datagram Socket

Advertisement

The following example implements a very simple networked communications client and server. Messages are
typed into the window at the server and written across the network to the client side, where they are
displayed.

Raw sockets provide ICMP (Internet Control Message Protocol) access. These sockets are usually datagram-
oriented, but their exact nature depends on the interface provided by the protocol. Raw sockets are not
suitable for most applications. It is provided to support the development of new communication protocols or
to access more complex features of existing protocols. Only root processes can use raw sockets. The socket
type is SOCK_RAW.

The main part of the Internet is the address. Every computer device on the Internet has one of its own. An
Internet address is a unique identifier number for each computer on the Net. Initially, all Internet addresses
were 32-bit values, classified as four 8-bit values. IPv4 (Internet Protocol, version 4) specifies this type of
address. However, a new address system, called IPv6 (Internet Protocol, version 6) is already in operation.
IPv6 uses a 128-bit value to represent the address, which is organized into eight 16-bit fragments. While
there are a few reasons and advantages for IPv6, the chief one is that it supports address space much larger
than the IPv4 does. To offer background compatibility with IPv4, IPv6 address can contain a valid IPv4 address
in its lower-order 32 bits. Thus, making IPv4 upwardly compatible with IPv6. Fortunately, if you are using
Java, whether we are using IPv4 or IPv6 addresses, these details are handled by the Java for us and we need
not to generally worry about it. Just as the numbers of an IP address define network sequence, the Internet
address' name, i.e., domain name, defines the location of the machine in a name space. For example,
'www.javatpoint.com' is in the COM domain (reserved commercial sites); it is called 'javatpoint' (after the
organization name), and 'www' identifies a web application server. An Internet domain name is mapped to
an IP address by the Domain Naming Service (DNS). This allows users to work with domain names, but the
Internet works for IP addresses.

The Interfaces and Networking Classes in Java supports TCP/IP both by extending the already established
stream I/O interface and by accumulating the features required to build I/O objects across the network. TCP
and UDP protocol families are both supported by Java. For reliable stream-based I/O across the network TCP
is used. UDP supports a simpler, hence faster, point-to-point datagram-oriented model.

Rocksaw is a simple API that runs I/O networks using IPv4 and IPv6 in Java. It provides ICMP access. ICMP is a
protocol that works on the network layer and is used by network devices to diagnose network
communication issues. It determines whether the data is reaching the intended destination in a timely
manner. It is crucial for error reporting and testing. ICMP a connectionless protocol: one device does not
need to open a connection with another device before sending an ICMP message.

Rocksaw is the de facto standard API for multi-platform raw socket programming in Java. It has been
deployed on several computing nodes as part of commercial products and custom enterprise applications.
The current version of RockSaw compiles on the following 32-bit and 64-bit platforms: Linux, Windows with
Cygwin/MinGW/Winsock or Visual C++, FreeBSD, and Darwin/Mac OS X. It should compile on other POSIX
systems using the GNU tool chain. Raw sockets are used to generate/receive packets of a type that the kernel
doesn't explicitly support.

A simple example of Raw Socket is PING. Ping works by sending ICMP echo packets (Internet Message
Control Protocol, an IP protocol other than TCP or UDP). The kernel has built-in code that responds to
echo/ping packets. It must conform to the TCP/IP specification. There is no code to create these packages
because they are not needed. So, instead of creating another system call with associated code in the kernel
to accomplish this, the "ping packet generator" is a user space program. It formats an ICMP echo packet and
sends it out over a SOCK_RAW, waiting for a response. That is why ping runs as set-uid root.

You might also like