0% found this document useful (0 votes)
21 views

Unit 3- JS,AJAX, Networking

This document provides an overview of JavaScript, detailing its characteristics as a client-side, interpreted, and object-based scripting language. It covers essential concepts such as variable scope, data types (primitive and non-primitive), operators, conditional statements, and loops, along with examples for each topic. The document serves as a foundational guide for understanding and incorporating JavaScript into web development.

Uploaded by

Nimisha Gupta
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)
21 views

Unit 3- JS,AJAX, Networking

This document provides an overview of JavaScript, detailing its characteristics as a client-side, interpreted, and object-based scripting language. It covers essential concepts such as variable scope, data types (primitive and non-primitive), operators, conditional statements, and loops, along with examples for each topic. The document serves as a foundational guide for understanding and incorporating JavaScript into web development.

Uploaded by

Nimisha Gupta
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/ 161

UNIT-3:

JAVASCRIPT
1. INTRODUCTION
a. Scripting language
b. Client-side language
c. Object-based language i.e. does not have polymorphism or inheritance or both
d. Interpreted language. The browser has the interpreter.
e. Light weighted and does not require server interaction. So, the response is
faster.
f. No API for networking, don't have the concept of file handling, multithreading,
and multi-processing.
g. User inputs can be validated before sending the data to the server.
2. INCORPORATING JAVASCRIPT
i. JS Code is written with the <script> tag
<script type="text/javascript">
document.write("CSE3A")
</script>
ii. Two ways:
a. Internally: embedding code in HTML. There is only one file i.e. file with a
.html extension
i. in the body tag
ii. in the head tag
b. Externally: in separate .js file. There will be two separate files. one with .js
extension and other .html
3. JAVASCRIPT COMMENTS
a. Single line comments: //
b. Multiple line comments: /* */
4. VARIABLE
var a = 10 or a = 1.02
4.1. CONVENTIONS
a. Names must start with a letter(a-z, A-Z), _ or $
b. 0-9
c. Case sensitive. a and A are different.

4.2. SCOPE OF A VARIABLE


a. Local Scope:
i. Function scope: Variables declared Locally (inside a function)
have Function Scope.
ii. Block scope: Variables declared with the var keyword cannot have Block
Scope.
Variables declared inside a block {} can be accessed from outside the block.
Before
ES2015 JavaScript did not have a Block Scope. Variables declared with
the let keyword can have Block Scope. Variables declared inside a
block {} cannot
be accessed from outside the block.

b. Global Scope: Variables declared Globally (outside any function)


have Global Scope. Global variables can be accessed from anywhere in a
JavaScript program.
5. DATA TYPES
JavaScript provides different data types to hold different types of values. There
are two types of data types in JavaScript.
1.Primitive data type
2.Non-primitive (reference) data type

JavaScript is a dynamically-typed language; means we don't need to specify


type the of variable because it is dynamically used by the JavaScript engine. It
can hold any type of value such as numbers, strings, etc. For example:
1.var a=5; //holding number
2.var b="CSE3A"; //holding string
5.1. PRIMITIVE DATA TYPES
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g., "hello"
Number represents numeric values e.g. 100.
Boolean represents boolean value either false or true
Undefined represents undefined value. undefined means "does not
exist
Null represents null i.e., no value at all. The property is
defined, but the object it refers to does not exist.
Numbers:
A number data type can be an integer, a floating-point value, an exponential
value, a ‘NaN’ or a ‘Infinity’.
var a=250; // integer value
var b=25.5; // a number containing a decimal
var c = 10e4 // an exponential value which evaluates
to 10*10000;

There are special numeric values e.g. NaN and Infinity.


If a number is divided by 0, the resulting value is infinity.
5/0; // results in infinity
The type of infinity is a number
typeof(infinity); // returns number
A ‘NaN’ results when we try to perform an operation on a number with a non-
numeric value
‘hi’ * 5; // returns NaN
typeof(NaN); // returns a number

We can also create a number literal by using the Number() function:


var c = Number(5);
console.log(c); // This will return 5

We can create a number object using the ‘new’ operator and the Number()
constructor:
var num1= new Number(5);
console.log(num1); // This will return 5
typeof(num1); // This will return ‘number’
String:
The string data type in JavaScript can be any group of characters enclosed by
single or double.
var str1 = “This is a string1”; // This is a string primitive type or string literal
var str2= ‘This is a string2’;

Alternatively, we can use the String() function to create a new string.


var str4 = String(‘hi’); // This creates a string literal with value ' ‘hi’

The String() function is also used to convert a non-string value to a string.


String(4); // This statement will create a string ‘4’
Like the ‘number’ and the ‘boolean’ data types, a ‘String’ object can be created
using the ‘new’ operator:
var str5= new String(“hello”); // This is a string
object
console.log(str4); // This will return the string
‘hello’
Boolean:
The boolean data type has only two values, true and false.
It is mostly used to check a logical condition.
Thus, Booleans are logical data types that can be used for the comparison of two
variables or to check a condition.
When we check the data type of ‘true’ or ‘false’ using typeof operator, it returns
a boolean.
typeof(true) // returns boolean
typeof(false) // returns boolean

Let’s see an example of comparison statement:


var a =5;
var b=6;
a==b // returns false

A boolean value is also used to check a condition in an expression:


if(a<b){
alert(a is a smaller number than b);
}
If the above condition ‘a < b’ is true, the alert will pop on the screen.
We can create a new Boolean variable using the Boolean() function.
var check = Boolean(expression); // If the expression evaluates to true, the
value of ‘check’ will be true or else it will
be false.
var check = Boolean(a<b); // the expression evaluates to true, thus the value
of check will be true.

The Boolean() function converts a non-boolean value to a boolean value.


var mystring = ‘hi there’;
Boolean(mystring); // This will result in true because the ‘mystring’ value
exists.
A Boolean object can be created using the new operator.
var booleanobj = new Boolean(true);

Here ‘booleanobj’ is a Boolean object.


Though we can create an object of the primitive data types, ‘number’,’boolean’
and ‘number’ it is advisable or good practice to use the primitive version of these
types.
Undefined:
Undefined data type means a variable that is not defined.
The variable is declared but doesn’t contain any value.
So, you can say that undefined means lack of value or unknown value.
var a;
console.log(a); // This will return undefined.

The variable ‘a’ has been declared but hasn’t been assigned a value yet.
We can assign a value to a:
a=5;
console.log(a); // This will return 5
Null:
The null in JavaScript is a data type that is represented by only one value,
the ‘null’ itself.
A null value means no value.
You can assign null to a variable to denote that currently, the variable does not
have any value but it will have later on.
A null value evaluates to false in a conditional expression.
So you don't have to use comparison operators like === or !== to check for null
values.
5.2. NON-PRIMITIVE DATA TYPES
The non-primitive data types are as follows:

Data Description
Type
Object represents instance through which we can access members
Array represents a group of similar values
RegExp represents regular expression
Date represents properties of date
6. OPERATORS
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are the following types of operators in JavaScript.
a) Arithmetic Operators
b) Comparison (Relational) Operators
c) Bitwise Operators
d) Logical Operators
e) Assignment Operators
f) Special Operators
6.1. ARITHMETIC OPERATORS
Arithmetic operators are used to performing arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
6.2. COMPARISON OPERATORS
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
6.3. BITWISE OPERATORS
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:

Operator Description Example


& Bitwise AND (10==20 & 20==33) =
false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
6.4. LOGICAL OPERATORS
The following operators are known as JavaScript logical operators.

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
6.5. ASSIGNMENT OPERATORS
The following operators are known as JavaScript assignment operators.

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
6.6. SPECIAL OPERATORS
The following operators are known as JavaScript special operators.

Operator Description
(?:) returns a value based on the condition. It is like if-else.
, allows multiple expressions to be evaluated as a single statement.
delete deletes a property from the object.
in checks if the object has the given property
instanceof checks if the object is an instance of a given type
new creates an instance (object)
typeof checks the type of object.
7. CONDITIONAL STATEMENTS
7.1 IF-ELSE
The if-else statement is used to execute the code whether the condition is true or
false. There are three forms of if statement in JavaScript.
1.If Statement
2.If else statement
3.if else if statement
7.1.1. IF STATEMENT
It evaluates the content only if the expression is true. The syntax of the JavaScript
if statement is given below.
if(expression){
//content to be evaluated
}
Let’s see the simple example of if statement in JavaScript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
7.1.2. IF...ELSE STATEMENT
It evaluates the content whether the condition is true or false. The syntax of the
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Let’s see the example of if-else statement in JavaScript to find out the even or
odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>

Output of the above example


a is even number
7.1.3. IF...ELSE IF STATEMENT
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
} else if(expression2){
//content to be evaluated if expression2 is true
} else if(expression3){
//content to be evaluated if expression3 is true
} else{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in JavaScript.
var a=20;
if(a==10){
document.write("a is equal to 10");
} else if(a==15){
document.write("a is equal to 15");
}else if(a==20){
document.write("a is equal to 20");
} else{
document.write("a is not equal to 10, 15 or 20");
}

Output of the above example


a is equal to 20
7.1.4. SWITCH
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in the previous
section. The syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if the above values are not matched;
}
Let’s see the simple example of switch statement in JavaScript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

Output of the above example


B Grade
The switch statement is fall-through i.e., all the cases will be evaluated if you
don't use the break statement.
Let’s understand the behavior of the switch statement in JavaScript.
<script>
var grade='A';
var result;
switch(grade){
case 'A':
result="A Grade";
case 'B':
result="B Grade";
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output of the above example
C Grade
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
Output of the above example
undefined B Grade C Grade No Grade
8. LOOPS
The loops are used to iterate the piece of code using for, while, do-while, or for-
in loops.
There are four types of loops in JavaScript.
1.for loop
2.while loop
3.do-while loop
4.for-in loop
8.1. FOR LOOP
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5
8.2. WHILE LOOP
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
8.3. DO WHILE LOOP
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25
10. FUNCTIONS
Functions are used to perform operations. Declared functions are not executed
immediately. They are "saved for later use", and will be executed later, whn they
are invoked (called upon). We can call the JavaScript function many times to
reuse the code.
Advantages of JavaScript function
There are mainly two advantages of JavaScript functions.
1.Code reusability: We can call a function several times so it saves coding.
2.Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
10.1. FUNCTION SYNTAX
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
Functions can have 0 or more arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
10.2. FUNCTION ARGUMENTS
We can call the function by passing arguments. Let’s see the example of a
function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
10.3. FUNCTION EXPRESSIONS
A JavaScript function can also be defined using an expression. A function
expression can be stored in a variable. After a function expression has been stored
in a variable, the variable can be used as a function.
<script>
var x = function (a, b) {return a * b};
document.write(x(4, 3));
</script>
The function above is actually an anonymous function (a function without a
name). Functions stored in variables do not need function names. They are
always invoked (called) using the variable name.
10.5. FUNCTION HOISTING
Hoisting is a JavaScript mechanism where variables and function declarations
are moved to the top of their scope before code execution. Inevitably, this means
that no matter where functions and variables are declared, they are moved to the
top of their scope regardless of whether their scope is global or local.
<script>
myFunction(5);

function myFunction(y) {
return y * y;
}
</script>
10.6. FUNCTION WITH RETURN VALUE
We can call a function that returns a value and use it in our program. Let’s see
the example of a function that returns a value.
<script>
function getInfo(){
return "hello ! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello! How r u?
11. DISPLAY POPUP MESSAGE BOX
JavaScript provides different built-in functions to display popup messages for
different purposes e.g. to display a simple message or display a message and
take the user's confirmation on it or display a popup to take a user's input value.
11.1. ALERT BOX
Use alert() function to display a popup message to the user. This popup will
have OK button to close the popup.
alert("This is alert box!"); // display string message

alert(100); // display 100

alert(true); // display true


The alert function can display messages of any data type e.g., string, number,
boolean, etc. There is no need to convert a message to string type.
11.2. CONFIRM BOX
Sometimes you need to take the user's confirmation to proceed. For example,
you want to take the user's confirmation before saving updated data or deleting
existing data. In this scenario, use JavaScript built-in function confirm(). The
confirm() function displays a popup message to the user with two
buttons, OK and Cancel. You can check which button the user has clicked and
proceed accordingly.
<script>
if (confirm("Do you want to save changes?") == true) {
document.write("Data saved successfully!")
} else {
document.write("Save Cancelled!")
}
</script>
11.3. PROMPT BOX
Sometimes you may need to take the user's input to do further actions on a web
page. For example, you want to calculate EMI based on users' preferred tenure
of the loan. For this kind of scenario, use JavaScript built-in function prompt().
The prompt function takes two string parameters. The first parameter is the
message to be displayed and the second parameter is the default value which
will be in the input text when the message is displayed.
Syntax:

prompt([string message], [string defaultValue]);

Example:
<script>
var tenure = prompt("Please enter preferred tenure in years", "15");
if (tenure != null) {
alert("You have entered " + tenure + " years" );
}
</script>
As you can see in the above example, we have specified a message as the first
parameter and default value "15" as the second parameter. The prompt function
returns a user-entered value. If the user has not entered anything then it returns
null. So, it is recommended to check null before proceeding.
Note:
The alert, confirm and prompt functions are global functions. So it can also be
called using window object like window.alert(), window.confirm() and
window.prompt().
Points to Remember:
1.Popup message can be shown using global functions - alert(), confirm() and
prompt().
2.alert() function displays popup message with 'Ok' button.
3.confirm() function display popup message with 'Ok' and 'Cancel' buttons. Use
confirm() function to take the user's confirmation to proceed.
4.prompt() function enables you to take the user's input with 'Ok' and 'Cancel'
buttons. prompt() function returns value entered by the user. It returns null if
the user does not provide any input value.
12. JAVASCRIPT USER-DEFINED OBJECTS
A JavaScript object is an entity having state and behavior (properties and
method). For example, car, pen, bike, chair, glass, keyboard, monitor, etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
12.1. CREATING OBJECTS
There are 3 ways to create objects.
i. By object literal
ii. By creating instance of Object directly (using the new keyword)
iii. By using an object constructor (using the new keyword)
BY OBJECT LITERAL
The syntax of creating an object using object literal is given below:
object = {property1:value1, property2:value2.....propertyN:valueN}
property and value pair are separated by: (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example


102 Shyam Kumar 40000
BY CREATING INSTANCE OF OBJECT
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create an object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Sumit Singh";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
101 Sumit Singh 50000
BY USING AN OBJECT CONSTRUCTOR
Here, you need to create a function with arguments. Each argument value can
be assigned to the current object by using this keyword.
This keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Rakesh",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Output of the above example
103 Rakesh 30000
12.3. DEFINING METHOD IN JAVASCRIPT OBJECT
We can define a method in the JavaScript object. But before defining the
method, we need to add a property in the function with the same name as the
method.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;

function changeSalary(otherSalary){ // can be defined outside/inside the constructor


this.salary=otherSalary;
}
}
e=new emp(103,"ABC",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>

Output of the above example


103 ABC 30000
103 ABC 45000
13. JS BUILT-IN OBJECTS: ARRAY
JavaScript array is an object that represents a collection of elements.
There are 2 ways to construct an array in JavaScript
1.Using array literal
2.Using new keyword
13.1. BY ARRAY LITERAL
The syntax of creating array using array literal is given below:
var arrayname = [value1, value2, .....,valueN];
for eg.
var elements = [1,2,3, ‘a’, ‘b’, ‘c’];
values are contained inside [ ] and separated by , (comma).
<script>
var ele=["A","B","C"];
for (i=0;i<ele.length;i++){
document.write(ele[i] + "<br/>");
}
</script>
The length property returns the length of an array.
Output of the above example
A
B
C
13.2. Using new keyword
The syntax of creating array directly is given below:
var arrayname = new Array();
Here, new keyword is used to create instance of array.
<script>
var i;
var ele = new Array();
ele[0] = "Arun";
ele[1] = "Varun";
ele[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Arun
Varun
John
Array’s Parameterized constructor
<script>
var emp=new Array("Jai", "Vijay", "Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Jai
Vijay
Smith
13.2. ARRAY METHODS
a. concat() Method
The JavaScript array concat() method combines two or more arrays and returns
a new string. This method doesn't make any change in the original array. Also,
it doesn’t remove the duplicate elements.
The concat() method is represented by the following syntax:
array.concat(arr1,arr2,....,arrn)

<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android
b. pop() method
The JavaScript array pop() method removes the last element from the given
array and returns that element. This method changes the length of the original
array.
Syntax:
The pop() method is represented by the following syntax:
array.pop()
Return
The last element of the given array.
Example 1
Here, we will pop an element from the given array.
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
</script>
Output:
Orginal array: AngularJS,Node.js,JQuery
Extracted element: JQuery
Remaining elements: AngulaJS,Node.js

Example 2
In this example, we will pop all the elements from the given array.
<script>
var arr=["AngulaJS","Node.js","JQuery"];
var len=arr.length;
for(var x=1;x<=len;x++)
{
document.writeln("Extracted element: "+arr.pop()+"<br>");
}
</script>
Output:
Extracted element: JQuery
Extracted element: Node.js
Extracted element: AngulaJS
c. push() method
The JavaScript array push() method adds one or more elements to the end of
the given array. This method changes the length of the original array.
Syntax
The push() method is represented by the following syntax:
array.push(element1,element2....elementn)
Parameter
element1, element2....elementn - The elements to be added.
Return
The original array with added elements.
Let's see some examples of push() method
Example 1
Here, we will add an element in the given array.
<script>
var arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>
Output:
AngularJS,Node.js,JQuery

Example 2
Let's see an example to add more than one element in the given array.
<script>
var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
document.writeln("Update array: "+arr);
</script>
Output:
Length before invoking push(): 2
Length after invoking push(): 4
Update array: AngularJS,Node.js,JQuery,Bootstrap

d. Array reverse() method


The JavaScript array reverse() method changes the sequence of elements of the
given array and returns the reverse sequence. In other words, the array’s last
element becomes the first and the first element becomes the last. This method
also made the changes in the original array.
Syntax
The reverse() method is represented by the following syntax:
array.reverse()
Return
The original array elements are in reverse order.
Example
<script>
var arr=["AngulaJS","Node.js","JQuery"];
var rev=arr.reverse();
document.writeln(rev);
</script>
Output:
JQuery,Node.js,AngulaJS
e. shift() method
The JavaScript array shift() method removes the first element of the given
array and returns that element. This method changes the length of the original
array.
Syntax
The shift() method is represented by the following syntax:
array. shift()
Return
The first element of an array.
Example
<script>
var arr=["AngularJS","Node.js","JQuery"];
var result=arr.shift();
document.writeln(result);
</script>
Output:
AngularJS
f. Array slice() method
The JavaScript array slice() method extracts the part of the given array and
returns it. This method doesn't change the original array. The slice() method
creates a new array. It does not remove any elements from the source array.
Similar to slicing in Python
Syntax
The slice() method is represented by the following syntax:
array.slice(start,end)
Parameter
start - It is optional. It represents the index from where the method starts to
extract the elements.
end - It is optional. It represents the index at where the method stops extracting
elements.
Return
A new array contains the extracted elements.
Example 1
Let's see a simple example to extract an element from the given array.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
Output:
Node.js

Example 2
Let's see one more example to extract various element from the given array.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(0,3);
document.writeln(result);
</script>
Output:
AngularJS,Node.js,JQuery
Example 3
In this example, we will provide the negative values as index to extract elements.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(-4,-1);
document.writeln(result);
</script>
Output:
AngularJS,Node.js,JQuery
g. sort() method
The JavaScript array sort() method is used to arrange the array elements in some
order. By default, sort() method follows the ascending order.
Syntax
The sort() method is represented by the following syntax:
array.sort(compareFunction)
Parameter
compareFunction - It is optional. It represents a function that provides an
alternative sort order.
Return
An array of sorted elements
Example 1
Let's see a simple example to sort the array of string elements.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>
Output:
AngularJS,Bootstrap,JQuery,Node.js

Example 2
<script>
var arr=[2,4,1,8,5];
var result=arr.sort();
document.writeln(result);
</script>
Output:
1,2,4,5,8

Any compareFunction has the following syntax:


function (a, b){
// sorting logic
// return a Number
}
The sort() method compares all values of the array by passing two values at a
time to the compareFunction. The two parameters a and b represent these two
values respectively.
The compareFunction should return a Number. This returned value is used to
sort the elements in the following way:
• If returned value < 0, a is sorted before b (a comes before b).
• If returned value > 0, b is sorted before a (b comes before a).

• If returned value == 0, a and b remain unchanged relative to each other.

Example 3. Sort the array using length:


// custom sorting an array of strings
var names = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben"];

function len_compare(a, b){


return a.length - b.length;
}

// sort according to string length


names.sort(len_compare);

console.log(names);
function len_compare(a, b){
return a.length - b.length;
}
Here:
• If a.length - b.length < 0, a comes before b. For example, "Adam" comes
before "Jeffrey" as 4 - 7 < 0.
• If a.length - b.length > 0, b comes before a. For example, "Danil" comes
after "Ben" as 5 - 3 > 0.
• If a.length - b.length == 0, their position is unchanged. For example, the relative

position of "Jeffrey" and "Fabiano" is unchanged because 7 - 7 == 0.

We can see that this results in the sorting of strings according to their length in
ascending order.
Example 4
Let's see an example to extract minimum value from an array.
<script>
var arr=[2,4,1,8,5]
var result=arr.sort(); //1,2,4,5,8
document.writeln(arr[0]);
</script>
Output:
1
Example 5
Let's see an example to extract maximum value from an array.
<script>
var arr=[2,4,1,8,5]
var result=arr.sort().reverse(); // 8,5,4,2,1
document.writeln(arr[0]);
</script>
Output:
8
h. toString() Method
The toString() method is used for converting and representing an array into
string form. It returns the string containing the specified array elements.
Commas separate these elements, and the string does not affect the original
array.
Syntax
The following syntax represents the toString() method:
array.toString()
Parameters
It does not have any parameters.
Return
It returns a string that contains all the elements of the specified array.
Example 1: Converting a given array into string form seperated by commas.
<html>
<head> <h3>Array Methods</h3> </br>
</head>
<body>
<script>
var arr=['a','b','c','d','e','f','g','h','i','j']; //array elements
var str=arr.toString(); //toString() method implementation
document.write("After converting into string: "+str);
</script>
</body>
</html>

Example2: Converting an array 'season' into string form.


<html>
<head>
<h3>Array Methods</h3> </br>
</head>
<body>
<script>
var season=["Spring","Autumn","Summer","Winter"];
var str=season.toString(); //toString() method implementation
document.write("After converting into string: "+str);
</script>
</body>
</html>
Example3: Converting an array containing numeric values into string.
<html>
<head>
<h5> Array Methods </h5> </br>
</head>
<body>
<script>
var arr=["1","2","3","4"];
document.write(arr.toString()); //After converting into string.
</script>
</br></br>
</body>
</html>
i. unshift() method
The JavaScript Array unshift() method adds one or more elements to the
beginning of an array and returns the new length of the array.
The syntax of the unshift() method is:

arr.unshift(element1, element2, ..., elementN)

Here, arr is an array.

unshift() Parameters
The unshift() method takes in an arbitrary number of elements to add to the
array.
Return value from unshift()
Returns the new (after adding arguments to the beginning of the array) length of
the array upon which the method was called.
Notes:
This method changes the original array and its length.
Example: Using unshift() method
var languages = ["JavaScript", "Python", "Java", "Lua"];
var count = languages.unshift("C++");
console.log(languages); // [ 'C++', 'JavaScript', 'Python', 'Java', 'Lua']
console.log(count); // 5

var priceList = [12, 21, 35];


var count1 = priceList.unshift(44, 10, 1.6);
console.log(priceList); // [ 44, 10, 1.6, 12, 21, 35]
console.log(count1); // 6
Output
[ 'C++', 'JavaScript', 'Python', 'Java', 'Lua']
5
[ 44, 10, 1.6, 12, 21, 35]
6
j. splice() method
The JavaScript Array splice() method returns an array by changing
(adding/removing) its elements in place.
The syntax of the splice() method is:

arr.splice(start, deleteCount, item1, ..., itemN)

Here, arr is an array.

splice() Parameters
The splice() method takes in:
• start - The index from where the array is changed.
• deleteCount (optional) - The number of items to remove from start.
• item1, ..., itemN (optional) - The elements to add to the start index. If not
specified, splice() will only remove elements from the array.
Return value from splice()
Returns an array containing the deleted elements.
Note: The splice() method changes the original array.

Example 1: Using splice() method


languages = ["JavaScript", "Python", "Java", "Lua"];

// replacing "Java" & "Lua" with "C" & "C++"


removed = languages.splice(2, 2, "C", "C++");
console.log(removed); // [ 'Java', 'Lua' ]
console.log(languages); // [ 'JavaScript', 'Python', 'C', 'C++' ]
// adding elements without deleting existing elements
removed1 = languages.splice(1, 0, "Java", "Lua");
console.log(removed1); // []
console.log(languages); // [ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]

// removing 3 elements
removed = languages.splice(2, 3);
console.log(removed2); // [ 'Lua', 'Python', 'C' ]
console.log(languages); // [ 'JavaScript', 'Java', 'C++' ]

Output
[ 'Java', 'Lua' ]
[ 'JavaScript', 'Python', 'C', 'C++' ]
[]
[ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]
[ 'Lua', 'Python', 'C' ]
[ 'JavaScript', 'Java', 'C++' ]

14. JS BUILT-IN OBJECTS: STRING


The String is an object that represents a sequence of characters.
There are 2 ways to create strings in JavaScript
i. By string literal
ii. By string object (using the new keyword)
i) BY STRING LITERAL
The string literal is created using double-quotes. The syntax of creating a string
using string literal is given below:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
This is string literal
ii) By string object (using new keyword)
The syntax of creating a string object using a new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

Output:
hello javascript string
14.2. STRING METHODS
Let's see the list of JavaScript string methods with examples.
a) charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
Output:
v
b) concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Output:
javascript concat example
c) indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the
given string.
<script>
var s1="javascript from indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output:
11
d) lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of
the given string.
<script>
var s1="javascript from indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output:
16
e) toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in
lowercase letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
Output:
javascript tolowercase example
f) toUpperCase() Method
The JavaScript String toUpperCase() method returns the given string in
uppercase letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
g) slice(beginIndex, endIndex) Method
The JavaScript String slice(beginIndex, endIndex) method returns the parts of
string from given beginIndex to endIndex. In slice() method, beginIndex is
inclusive and endIndex is exclusive.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output:
cde
h) trim() Method
The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Output:
javascript trim
i) split() Method
<script>
var str="This is javascript";
document.write(str.split(" ")); //splits the given string.
</script>
15. EVENT HANDLING
15.1. INTRODUCTION TO EVENT HANDLING

• Event Handling is a routine that processes actions, such as keystrokes and


mouse movements.
• It is the receipt of an event at some event handler from an event producer and
subsequent processes.
15.3. EVENT HANDLERS
Event Handler Description
onAbort It executes when the user aborts loading an image.
It executes when the input focus leaves the field of a text,
onBlur
textarea or a select option.
It executes when the input focus exits the field after the user
onChange
modifies its text.
In this, a function is called when an object in a button is
onClick clicked, a link is pushed, a checkbox is checked or an image
map is selected.
It executes when an error occurs while loading a document or
onError
an image.
It executes when input focus enters the field by tabbing in or
onFocus
by clicking but not selecting input from the field.
onLoad It executes when a window or image finishes loading.
The JavaScript code is called when the mouse is placed over a
onMouseOver
specific link or an object.
The JavaScript code is called when the mouse leaves a
onMouseOut
specific link or an object.
It executes when the user resets a form by clicking on the
onReset
reset button.
It executes when the user selects some of the text within a text
onSelect
or textarea field.
onSubmit It calls when the form is submitted.
onUnload It calls when a document is exited.
15.4. EXAMPLES
15.4.1. MOUSE EVENTS
15.4.2. CLICK EVENT
Submit
Button
15.4.3. ONLOAD EVENT
15.4.4. KEY EVENTS
16. FORM VALIDATION
16.1. NAME AND PASSWORD VALIDATION
15.2. VALIDATING DROPDOWN
15.3. VALIDATING EMAIL ADDRESS
15.4. CONFIRM PASSWORD VALIDATION
UNIT 3: AJAX - ASYNCHRONOUS JAVASCRIPT AND
XML
INTRODUCTION

AJAX is a client-side technique. With AJAX, we are able to make


background server calls for fetching additional data, and updating some portions of the
web page without refreshing the whole page.
In other words, AJAX allows web pages to be updated asynchronously by exchanging
small amounts of data with the server behind the scenes. If an application is not using
AJAX, it will have to load a new webpage on every request user made.
AJAX is based on JavaScript and HTTP requests.
AJAX is not a new programming language, but a new way to use existing standards
with DOM manipulating.
JavaScript helps an AJAX to make background AJAX calls for fetching a certain amount
of data.
Without AJAX, traditional web page takes a longer time to finishing round
trip process for getting a data form the server. So, it's time-consuming
process even if small changes are in web page, entire web page reload.
In a traditional webpage, you can't update small portion without reloading
page. So here AJAX is help us to background server calls for fetching data
and update new contain without reloading page.
AJAX is a type of programming made popular in 2005 by Google (with
Google Suggest).
2.BENEFITS OF AJAX

Using AJAX, you can create better, faster, and more user-friendly web
applications.
AJAX is based on JavaScript, CSS, HTML and XML etc. So, you can easily
learn.
AJAX behaviour and works is like a desktop application. So, Ajax use for
creating a rich web application.
3.HOW DOES AJAX WORKS?

Without AJAX, whenever we want to access account, we press login link.


New login page open and enter username, password, and login successfully.
It's time-consuming process, inefficient for only small amount data (Login
page) exchange required.
With AJAX, we want to access account, we press login link. Background
JavaScript call to a server for fetching login portion and update/add to current
web page. Now, we can enter username, password and login successfully. It
takes small bit of time for this process.
HOW DOES AJAX WORKS? (Contd…)
It is essential to understand that AJAX is not a single technology but a group
of technologies, e.g. HTML, CSS, DOM, and JavaScript, etc. HTML and CSS
can be used in combination to mark up and style information of the webpage.

HTML/CSS is website markup language for defining web page layout, such
as fonts style and colours.
JavaScript special object XMLHttpRequest that was designed by Microsoft.
XMLHttpRequest provides an easy way to retrieve data from web server
without having to do full page refresh. Web page can update just part of the
page without interrupting what the users are doing.
Document Object Model (DOM) method provides a tree structure as a
logical view of web page.
XML for retrieving any type of data, not just XML data from the web server.
However, you can use other formats such as Plain text, HTML or JSON
(JavaScript Object Notation). and it supports protocols HTTP and FTP.
The DOM is accessed with JavaScript to dynamically display the
information, and allow the user to interact with, the information presented.
JavaScript and the XMLHttpRequest object provide a method for
exchanging data asynchronously between the browser and the server to avoid
full page reloads.

Note: In recent years, the essence of XML has been


reduced. JSON (JavaScript Object Notation) is often used as an alternative
format for data interchange, although other formats such as preformatted
HTML or plain text can also be used for data purpose.
4. AJAX LIFE CYCLE
Normally, sending an AJAX request to the server and getting back the
response (life cycle events) from the server involve the following steps:
• User type the URL of a webpage in the browser’s address bar and hit
ENTER. The page is loaded in browser.
• Some user action triggers an event, like the user clicking a button.
• Event fires the AJAX call, and sends a request to a server.
• The server takes the input from AJAX request, and processes the request.
The server also prepares the response if required.
• The server sends the data back to the webpage that made the request.
• Another JavaScript function, called a callback function, receives the data
in the server response, and updates the web page.
AJAX Lifecycle
4. AJAX XMLHttpRequest Object
The core of AJAX is the XMLHttpRequest object (available in client-side
scripting languages like JavaScript). The XMLHttpRequest object is used to
exchange the data with a live server behind the scenes. All modern browsers
(IE, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest
object.

If you are using IE 5 or IE6 (I wonder if someone still uses it),


then ActiveXObject will be used for server communication to send ajax
requests.
4.1. CREATE XMLHttpRequest OBJECT
A new object of XMLHttpRequest is created like this:
//Creating a new XMLHttpRequest object
var xmlhttp;

if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera,
Safari
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
This xmlhttp variable can be re-used to send multiple ajax requests, without
creating a new object for each request.
4.2. XMLHttpRequest METHODS
To send requests and set request attributes, XMLHttpRequest object provides
following methods:

4.2.1. open(method, url, isAsync, userName, password)


The HTTP and HTTPS requests of the XMLHttpRequest object must be
initialized through the open() method. The open() specifies the type of request
(GET, POST etc.), the request URL, and if the request should be handled
asynchronously or not.
The 4th and 5th parameters are the username and password, respectively. These
parameters can be provided for authentication and authorization purposes if the
server needs it.

The XMLHttpRequest method open() initializes a newly-


created request, or re-initializes an existing one.
Syntax
Open(“method”, URL[,asynchronous, flag[, “username”[, “password”]]

PARAMETER REQUIRED DESCRIPTION


method required Specifies the HTTP method.
Valid value GET, POST, HEAD, PUT, DELETE, OPTIONS

required Specifies URL that may be either relative parameter or absolute full
URL
URL.

asynchronous_flag optional Specifies whether the request should be handled asynchronously or


not.
Valid values: true, false
Default value: true
true means process the next statement in the code without waiting
for a response
false means wait for a response
optional Specifies username of authorize user otherwise set to null.
username
optional Specifies password of authorize user otherwise set to null.
password
xhr.open("GET","report_data.xml",true);
xhr.open("GET","sensitive_data.xml",false);
xhr.open("POST","saveData",true,"myUserName","somePassord");

4.2.2. setRequestHeader(name, value)


Upon successful initialization of a request, the setRequestHeader() method of
the XMLHttpRequest object can be invoked to set HTTP headers in the request.

xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("User-Agent", "navigator.userAgent");
4.2.3. send(payload)
To finally send an HTTP request, the send() method of
the XMLHttpRequest must be invoked. This method accepts a single parameter
containing the request body to be sent with the request. The payload is necessary
in POST requests. For GET and HEAD methods, simply pass null as a
parameter.

xhr.send(null); //HTTP GET


xhr.send( '{"id":"23423"}' ); //HTTP POST

4.2.4. abort()
It aborts the request if the readyState of the XMLHttpRequest object has not yet
become 4 (request complete). The abort() method ensures that the callback
method does not get invoked in an asynchronous request.

xhr.abort();
5. ASYNCHRONOUS AND SYNCHRONOUS AJAX REQUESTS
XMLHttpRequest object is capable of sending synchronous and asynchronous
requests, as required from the webpage. This behaviour is controlled by the third
parameter of open() method.
This parameter is set to:
• true – asynchronous requests
• false – synchronous requests
//Asynchronous request as third parameter is true
xhr.open("GET", "report_data.xml", true);
//Synchronous request as third parameter is false
xhr.open("GET", "report_data.xml", false);
The default value is true if it is not provided.
Asynchronous AJAX Requests do not block the webpage, and the user can
continue to interact with the other elements on the page while the server is
processing the request.
We should always use asynchronous AJAX requests because a synchronous
AJAX Request makes the browser unresponsive. It means the user will not be
able to interact with the webpage until the request is complete.
ASYNCHRONOUS AJAX REQUEST
Given below is a JavaScript program to show how to make
asynchronous requests with AJAX.
var request = new XMLHttpRequest();
request.open('GET','/bar/foo.txt',true);
//"true" makes the request asynchronous

request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200){
//request succeed
}else{
//request failed
}
}
};
request.send(null)
onreadystatechange Event
• onreadystatechange is an event listener registered with
XMLHttpRequest request.
• onreadystatechange stores a function that will process the response returned from
the server.
• The function will be called for all important events in the request’s life cycle.
Every time a step is completed in the request processing, the value of the
readyState property will be changed and set to one of the given integer values:
•0: request is not initialized, i.e., After the XMLHttpRequest object is created, the
open() is yet to be called.
•1: server connection established, i.e., After open() method called but send()
method is yet to be called.
•2: request received, i.e., After send() method is called.
•3: processing request, i.e., After the browser has established communication with
the server, but before the server has completed the response
•4: request finished and response is ready to be handled, i.e., After the request has
been completed, and the response data has been completely received from the
server.
Value State Description

0 UNSENT Client has been created. open() not called yet.

1 OPENED open() has been called.

send() has been called, and headers and status are


2 HEADERS_RECEIVED
available.

3 LOADING Downloading; responseText holds partial data.

4 DONE The operation is complete.


5.3. HANDLING RESPONSE FROM SERVER
To fetch the response sent from the
server, responseText or responseXML property of the XMLHttpRequest object
is used. If the response from the server is XML, and you want to parse it as an
XML object, use the responseXML property. If the response from the server is
not XML, use the responseText property.
• responseText : Get the response from server as a string

• responseXML : Get the response from server as XML

Given below is a JavaScript program that fetches the response sent from the
server for an AJAX request:
if (xhr.readyState == 4 && xhr.status == 200){
document.getElementById("message").innerHTML = xhr.responseText;
}
else {
alert('Something is wrong !!');
}
}
<html>
<head>
<script>
var request;
function sendInfo() {
var v=document.vinform.t1.value;
var url="index.jsp?val="+v;

if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}

try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}catch(e){
alert("Unable to connect to server");
}
}

function getInfo(){
if(request.readyState==4){
if (request.status == 200){
var val=request.responseText;
document.getElementById('display').innerHTML=val;
}
}
}
</script>
</head>
<body>
<form name="vinform">
<input type="text" name="t1">
<input type="button" value="ShowTable" onClick="sendInfo()">
</form>
<span id="display"> </span>
</body>
</html>
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

Networking Terminology
The widely used java networking terminologies are given below:

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.

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 communication

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.

a. The Socket class is used to communicate client and server. Through this class, we can read and
write message.
b. 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

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with 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

1) public Socket accept() returns the socket and establish a connection between server
and client.

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

Example 1:

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 connect with the given port
number, it returns an instance of Socket.

ServerSocket ss=new ServerSocket(6666);


Socket s=ss.accept(); //establishes connection and waits for the client

Creating Client:

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.

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: CSEServer.java

import java.io.*;
import java.net.*;

public class CSEServer {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
System.out.println("Server waiting . . .");
Socket s = ss.accept();
System.out.println("Client Connected !!!");
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Note: The readUTF() method of DataInputStream class reads a string that has been encoded using
a modified UTF-8 format and returned a String

File: CSEClient.java

import java.io.*;
import java.net.*;

public class CSEClient {


public static void main(String[] args) {
try {
System.out.println("Trying to connect with server . . .");
Socket s = new Socket("localhost", 80);
System.out.println("Connected to Server!!!");
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello CSE Server");
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Note: writeUTF(String str) method writes primitive data write of this String in modified UTF-8
format

To execute this program, open two command prompts and execute each program at each command
prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server console.
Example 2:
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.

File: CSEChatServer.java

class CSEChatServer {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(1111);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop")) {
str = din.readUTF();
System.out.println("client says: " + str);
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}

File: CSEChatClient.java

import java.net.*;
import java.io.*;

class CSEChatClient {
public static void main(String args[]) throws Exception {
Socket s = new Socket("127.0.0.1", 1111);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop")) {
str = br.readLine();
dout.writeUTF(str);
dout.flush();
str2 = din.readUTF();
System.out.println("Server says: " + str2);
}
dout.close();
s.close();
}
}

You might also like