Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Unit 3

Scripting: Java script: Introduction, documents, forms, statements, functions, objects;


introduction to AJAX, Networking : Internet Addressing, InetAddress, Factory
Methods, Instance Methods, TCP/IP Client Sockets, URL, URL Connection, TCP/IP
Server Sockets, Datagram.

What is JavaScript?
HTML and CSS concentrate on a static rendering of a page; things do not change on the
page overtime, or because of events.
To do these things, we use scripting languages, which allow content to change dynamically.
Not only this, but it is possible to interact with the user beyond what is possible with HTML.
Scripts are programs just like any other programming language; they can execute on the
client side or the server.

Advantages of client side scripting


The web browser uses its own resources, and eases the burden on the server.
It has fewer features than server side scripting.
It saves network bandwidth.

Disadvantages of client side scripting


Code is usually visible.
Code is probably modifiable.
Local files and databases cannot be accessed.
User is able to disable client side scripting.

Differentiate between server side and client side scripting languages

Client-side scripting languages


The client-side environment used to run scripts is usually a browser.
The processing takes place on the end users computer.
The source code is transferred from the web server to the user’s computer over the internet
and run directly in the browser.
The scripting language needs to be enabled on the client computer.
Sometimes if a user is conscious of security risks they may switch the scripting facility off.
When this is the case a message usually pops up to alert the user when script is attempting to
run.
Server-side scripting languages
The server-side environment that runs a scripting language is a web server.
A user's request is fulfilled by running a script directly on the web server to generate
dynamic HTML pages.
This HTML is then sent to the client browser.
It is usually used to provide interactive web sites that interface to databases or other data
stores onthe server.
\This is different from client-side scripting where scripts are run by the viewing web
browser, usually in JavaScript.
The primary advantage to server-side scripting is the ability to highly customize the
response basedon the user's requirements, access rights, or queries into data stores.

What is difference between Java script and JAVA?


Java is a statically typed language; JavaScript is dynamic.
Java is class-based; JavaScript is prototype-based.
Java constructors are special functions that can only be called at object creation;
JavaScript"constructors" are just standard functions.
Java requires all non-block statements to end with a semicolon; JavaScript inserts
semicolons at theends of certain lines.
Java uses block-based scoping; JavaScript uses function-based scoping.
Java has an implicit this scope for non-static methods, and implicit class scope; JavaScript
has implicit global scope.

Embedded JavaScript
JavaScript can be embedded in an HTML document.
To embed it in HTML you must write:
<script type=”text/javascript”>
</script>

The script tag has effect of the stopping the JavaScript being printed out as well as
indentifying the code enclosed.
The JavaScript can be placed in the head section of your HTML or the body.
<html>
<body>
<script type=”text/javascript”>
document.write("<h1>This is a
heading</h1>");
</script>
</body>
</html>
The Scripts placed in the body section are executed as the page loads and can be used to
generatethe content of the page.
As well as the body section, JavaScript can also be placed in the head part.
The advantages of putting a script in there are that it loads before the main body.
External JavaScript
If you want to use the same script on several pages it could be a good idea to place the code
in aseparate file, rather than writing it on each.
That way if you want to update the code, or change it, you only need to do it once.
Simply take the code you want in a separate file out of your program and save it with the
extension
.js.
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

JavaScript Variables
Variables in JavaScript behave the same as variables in most popular programming
languages (C,C++, etc) do, but in JavaScript you don't have to declare variables before you
use them.
A variable's purpose is to store information so that it can be used later. A variable is a
symbolic name that represents some data that you set.
When using a variable for the first time it is not necessary to use "var" before the variable
name.
Variable names must begin with a letter.
Variable names are case sensitive (y and Y are different variables).
var x=5;
var y=6;
var
z=x+y;
You can declare many variables in one statement. Just start the statement with var and
separate thevariables by comma:
var name="Doe", age=30,
job="carpenter";var name="Doe",
age=30,
job="carpenter";
Variable declared without a value will have the value undefined.
If you re-declare a JavaScript variable, it will not lose its value.
The value of the variable carname will still have the value "Volvo" after the execution of
thefollowing two statements.
varcarname="Volvo
";varcarname;

JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming
languages.
The definition of an operator is a symbol that is used to perform an operation.
Most often these operations are arithmetic (addition, subtraction, etc), but not always.
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 + (Addition) Ex: A + B will give 30

2 - (Subtraction) Ex: A - B will give -10

3 * (Multiplication) Ex: A * B will give 200

4 / (Division) Ex: B / A will give 2

5 % (Modulus) Ex: B % A will give 0

6 ++ (Increment) Ex: A++ will give 11


7 -- (Decrement) Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.

3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.

4 < (Less than)


Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.

Bitwise Operators
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −

Sr.No. Operator & Description

1
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2
| (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.

4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.

5 << (Left Shift)


It moves all the bits in its first operand to the left by the number of places specified in
the second operand. New bits are filled with zeros. Shifting a value left by one position
is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by
4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved right by the number of
bits specified by the right operand.
Ex: (A >> 1) is 1.

Assignment Operators
JavaScript supports the following assignment operators −

Sr.No. Operator & Description

1 = (Simple Assignment ) Ex: C = A + B will assign the value of A + B into C

2
+= (Add and Assignment) Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment) Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment) Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment) Ex: C /= A is equivalent to C = C / A


Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.

Sr.No. Operator and Description

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

Example
Try the following code to understand how the Conditional Operator works in JavaScript.

Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try..
JavaScript - if...else Statement
 While writing a program, there may be a situation when you need to adopt one out of a
given set of paths. In such cases, you need to use conditional statements that allow your
program to make correct decisions and perform right actions.
 JavaScript supports conditional statements which are used to perform different actions
based on different conditions. Here we will explain the if..else statement.

if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.

Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
Maths Book
Set the variable to different value and then try...
JavaScript - Switch Case
 You can use multiple if...else…if statements, as in the previous chapter, to perform a
multiway branch. However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable.
 Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else if statements.
 The objective of a switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)


break;

default: statement(s) }
JavaScript - While Loops
 While writing a program, you may encounter a situation where you need to perform an
action over and over again. In such situations, you would need to write loop statements to
reduce the number of lines.
 JavaScript supports all the necessary loops to ease down the pressure of programming.
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The
purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
Live Demo
<html>
<body>

<script type = "text/javascript">


<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

The do...while Loop


The do...while loop is similar to the while loop except that the condition check happens at the end
of the loop. This means that the loop will always be executed at least once, even if the condition
is false.
Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
JavaScript - For Loop
The 'for' loop is the most compact form of looping. It includes the following three important parts

 The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true,
then the code given inside the loop will be executed, otherwise the control will come out of
the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
Live Demo
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions
like alert() and write() in the earlier chapters. We were using these functions again and again, but
they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your
own functions in JavaScript.

Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A function can take multiple parameters
separated by comma.

Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons
to close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains
a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.
Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

JavaScript - The Arrays Object


The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.

Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter
with the Array constructor, you specify the initial length of the array. The maximum length allowed
for an array is 4,294,967,295.
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
JavaScript - Objects Overview
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be
called object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or methods,
together in an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of classes) for
some of its properties and methods.
 Polymorphism − the capability to write one function or method that works in a variety of
different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.

Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title" property of
the document object.
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There is
a small difference between a function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of document
object to write any content on the document.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.

The new Operator


The new operator is used to create an instance of an object. To create an object, the new operator
is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These
constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object() to build the object. The return value of
the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not
variables and are not defined with the var keyword.

Example 1
Try the following example; it demonstrates how to create an Object.
Live Demo
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output
Book name is : Perl
Book author is : Mohtashim
Example 2
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
Live Demo
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example
Try the following example; it shows how to add a function along with an object.
Live Demo
<html>

<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}

function book(title, author) {


this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");


document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim Book price is : 100
Create a JavaScript Calculator using the JavaScript, HTML and CSS
programming languages.
1.
2. <!-
- Create a simple Program to build the Calculator in JavaScript using with HTML and CSS web lan
guages. -->
3. <!DOCTYPE html>
4. <html lang = "en">
5. <head>
6. <title> JavaScript Calculator </title>
7.
8. <style>
9. h1 {
10. text-align: center;
11. padding: 23px;
12. background-color: skyblue;
13. color: white;
14. }
15.
16. #clear{
17. width: 270px;
18. border: 3px solid gray;
19. border-radius: 3px;
20. padding: 20px;
21. background-color: red;
22. }
23.
24. .formstyle
25. {
26. width: 300px;
27. height: 530px;
28. margin: auto;
29. border: 3px solid skyblue;
30. border-radius: 5px;
31. padding: 20px;
32. }
33.
34.
35.
36. input
37. {
38. width: 20px;
39. background-color: green;
40. color: white;
41. border: 3px solid gray;
42. border-radius: 5px;
43. padding: 26px;
44. margin: 5px;
45. font-size: 15px;
46. }
47.
48.
49. #calc{
50. width: 250px;
51. border: 5px solid black;
52. border-radius: 3px;
53. padding: 20px;
54. margin: auto;
55. }
56.
57. </style>
58.
59. </head>
60. <body>
61. <h1> Calculator Program in JavaScript </h1>
62. <div class= "formstyle">
63. <form name = "form1">
64.
65. <!-- This input box shows the button pressed by the user in calculator. -->
66. <input id = "calc" type ="text" name = "answer"> <br> <br>
67. <!-- Display the calculator button on the screen. -->
68. <!-- onclick() function display the number prsses by the user. -->
69. <input type = "button" value = "1" onclick = "form1.answer.value += '1' ">
70. <input type = "button" value = "2" onclick = "form1.answer.value += '2' ">
71. <input type = "button" value = "3" onclick = "form1.answer.value += '3' ">
72. <input type = "button" value = "+" onclick = "form1.answer.value += '+' ">
73. <br> <br>
74.
75. <input type = "button" value = "4" onclick = "form1.answer.value += '4' ">
76. <input type = "button" value = "5" onclick = "form1.answer.value += '5' ">
77. <input type = "button" value = "6" onclick = "form1.answer.value += '6' ">
78. <input type = "button" value = "-" onclick = "form1.answer.value += '-' ">
79. <br> <br>
80.
81. <input type = "button" value = "7" onclick = "form1.answer.value += '7' ">
82. <input type = "button" value = "8" onclick = "form1.answer.value += '8' ">
83. <input type = "button" value = "9" onclick = "form1.answer.value += '9' ">
84. <input type = "button" value = "*" onclick = "form1.answer.value += '*' ">
85. <br> <br>
86.
87.
88. <input type = "button" value = "/" onclick = "form1.answer.value += '/' ">
89. <input type = "button" value = "0" onclick = "form1.answer.value += '0' ">
90. <input type = "button" value = "." onclick = "form1.answer.value += '.' ">
91. <!-
- When we click on the '=' button, the onclick() shows the sum results on the calculator screen. --
>
92. <input type = "button" value = "=" onclick = "form1.answer.value = eval(form1.answer.value) "
>
93. <br>
94. <!-- Display the Cancel button and erase all data entered by the user. -->
95. <input type = "button" value = "Clear All" onclick = "form1.answer.value = ' ' " id= "clear" >
96. <br>
97.
98. </form>
99. </div>
100. </body>
101. </html>
JavaScript function to check whether a textbox is either empty or not :

JavaScript: Display the current day and time in


a specific format
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday","Monday","Tuesday","Wednesday
","Thursday","Friday","Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12)? " PM ":" AM ";
hour = (hour >= 12)? hour - 12: hour;
console.log("Current Time : "+hour + prepand + " : " + minute + " : " +
second);
AJAX = Asynchronous JavaScript and XML.
 AJAX = Asynchronous JavaScript and XML.
 AJAX is not a new programming language, but a new way to use existing standards.
 AJAX is the art of exchanging data with a server, and updating parts of a web page - without
reloading the whole page.
 What is AJAX?
 AJAX = Asynchronous JavaScript and XML.
 AJAX is a technique for creating fast and dynamic web pages.
 AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with
the server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
 Classic web pages, (which do not use AJAX) must reload the entire page if the content should
change.
 Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
 AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related
technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
 AJAX allows you to send and receive data asynchronously without reloading the web page.
So it is fast.
 AJAX allows you to send only important information to the server not the entire page. So
only valuable data from the client side is routed to the server side. It makes your application
interactive and faster.

Synchronous (Classic Web-Application Model)


A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In
such case, javascript engine of the browser is blocked.

As you can see in the above image, full page is refreshed at request time and user is blocked until
request completes.
Let's understand it another way.

Asynchronous (AJAX Web-Application Model)


An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can
perform another operations also. In such case, javascript engine of the browser is not blocked.

As you can see in the above image, full page is not refreshed at request time and user gets
response from the ajax engine.

Let's try to understand asynchronous communication by the image given below.


How AJAX Works

Why to Learn Ajax?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and
more interactive web applications with the help of XML, HTML, CSS, and Java Script.
 Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
 Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
 With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results,
and update the current screen. In the purest sense, the user would never know that anything was
even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any format, including plain
text, can be used.
 AJAX is a web browser technology independent of web server software.
 A user can continue to use the application while the client program requests information from the
server in the background.
 Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event
trigger.
 Data-driven as opposed to page-driven.

AJAX cannot work independently. It is used in combination with other technologies to create interactive
webpages.

AJAX Technologies
As describe earlier, ajax is not a technology but group of inter-related
technologies. AJAX technologies includes:
o HTML/XHTML and CSS
o DOM
o XML or JSON
o XMLHttpRequest
o JavaScript

HTML/XHTML and CSS


These technologies are used for displaying content and style. It is mainly used for presentation.

DOM
It is used for dynamic display and interaction with data.

XML or JSON
For carrying data to and from server. JSON (Javascript Object Notation) is like XML but short and
faster than XML.

XMLHttpRequest
For asynchronous communication between client and server. For more visit next page.

JavaScript
It is used to bring above technologies together.

Independently, it is used mainly for client-side validation.

How AJAX works?


AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow
of ajax or how ajax works by the image displayed below.
As you can see in the above example, XMLHttpRequest object plays a important role.

1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
Network Addressing
What is an IP Address?
An IP (Internet Protocol) address is a numerical label assigned to the devices connected to a computer
network that uses the IP for communication.

IP address act as an identifier for a specific machine on a particular network. It also helps you to develop a
virtual connection between a destination and a source. The IP address is also called IP number or internet
address. It helps you to specify the technical format of the addressing and packets scheme. Most networks
combine TCP with IP.

An IP address consists of four numbers, each number contains one to three digits, with a single dot (.)
separates each number or set of digits.

Parts of IP address
IP Address is divided into two parts:

 Prefix: The prefix part of IP address identifies the physical network to which the computer is
attached. . Prefix is also known as a network address.
 Suffix: The suffix part identifies the individual computer on the network. The suffix is also called
the host address.

Types of IP4 Classes


IP Header Classes:
Address Subnet Example Leading Max number of
Class Application
Range masking IP bits networks
IP
Class 1 to 126 255.0.0.0 1.1.1.1 8 128 Used for large number of hosts.
A
IP
128 to 191 255.255.0.0 128.1.1.1 16 16384 Used for medium size network.
Class B

IP
192 to 223 255.255.255.0 192.1.11. 24 2097157 Used for local area network.
Class C
IP
Class 224 to 239 NA NA NA NA Reserve for multi-tasking.
D
This class is reserved for
IP
240 to 254 NA NA NA NA research and Development
Class E
Purposes.

How does IP address work?


 IP address works in an IP network like a postal address. For example, a postal address combines
two addresses, address, or your area your house address.
 The address or your area is a group address of all houses that belong to a specific area. The house
address is the unique address of your homes in that area. Here, your area is represented by a PIN
code number.
 In this example, the network address comprises all hosts which belong to a specific network. The
host address is the unique address of a particular host in that network.

Class A Network
 This IP address class is used when there are a large number of hosts. In a Class A type of network,
the first 8 bits (also called the first octet) identify the network, and the remaining have 24 bits for
the host into that network.
 An example of a Class A address is 102.168.212.226. Here, “102” helps you identify the network
and 168.212.226 identify the host.
 Class A addresses 127.0.0.0 to 127.255.255.255 cannot be used and is reserved for loopback and
diagnostic functions.

Class B Network
In a B class IP address, the binary addresses start with 10. In this IP address, the class decimal number that
can be between 128 to 191. The number 127 is reserved for loopback, which is used for internal testing on
the local machine. The first 16 bits (known as two octets) help you identify the network. The other
remaining 16 bits indicate the host within the network.

An example of Class B IP address is 168.212.226.204, where *168 212* identifies the network and
*226.204* helps you identify the Hut network host.
Class C Network
Class C is a type of IP address that is used for the small network. In this class, three octets are used to
indent the network. This IP ranges between 192 to 223.

In this type of network addressing method, the first two bits are set to be 1, and the third bit is set to 0,
which makes the first 24 bits of the address them and the remaining bit as the host address. Mostly local
area network used Class C IP address to connect with the network.

Example for a Class C IP address: 192.168.178.1

Class D Network
Class D addresses are only used for multicasting applications. Class D is never used for regular
networking operations. This class addresses the first three bits set to “1” and their fourth bit set to use for
“0”. Class D addresses are 32-bit network addresses. All the values within the range are used to identify
multicast groups uniquely.

Therefore, there is no requirement to extract the host address from the IP address, so Class D does not
have any subnet mask.

Example for a Class D IP address: 227.21.6.173

Class E Network
Class E IP address is defined by including the starting four network address bits as 1, which allows you
two to incorporate addresses from 240.0.0.0 to 255.255.255.255. However, E class is reserved, and its
usage is never defined. Therefore, many network implementations discard these addresses as undefined or
illegal.

Example for a Class E IP address: 243.164.89.28

Limitations of classful IP addressing


Here are the drawbacks/ cons of the classful IP addressing method:

 Risk of running out of address space soon


 Class boundaries did not encourage efficient allocation of address space

Rules for assigning Network ID:


The network ID will be assigned based on the below-given rules:

 The network ID cannot start with 127 because 127 belongs to class A address and is reserved for
internal loopback functions.
 All bits of network ID set to 1 are reserved for use as an IP broadcast address and cannot be used.
 All bits of network ID are set to 0. They are used to denote a particular host on the local network
and should not be routed.
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.

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.

public String toString() it returns the string representation of the URL.

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

public String getDefaultPort() it returns the default port 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. }
Introduction: What Is a Network?
A network is a collection of devices that share a common communication protocol and a
common communication medium (such as network cables, dial-up connections, and wireless
links).
The term Network programming refers to writing programs that execute across multiple
devices (computers) in which the devices are all connected to each other using a network.

⚫ Client-Server Computing
At a basic level, network-based systems consist of a server , client , and a media for
communication as shown in next slide figure.

A computer running a program that makes a request for services is called client machine.
A computer running a program that offers requested services from one or more clients is
called server machine.
The media for communication can be wired or wireless Network\

Hosts Identification
Every computer on the Internet is identified by a unique, 4-byte IP address . This is typically
written in dotted octet format like 128.250.25.158 where each byte is an unsigned value
between 0 and 255.
This representation is clearly not user-friendly because it does not tell us anything about
the content and then it is difficult toremember. Hence, IP addresses are mapped to names
like www.yahoo.com or www.google.com, which are easier to remember.
Internet supports name servers that translate these names to IPaddresses. Domain Naming
Service (DNS) maps names to numbers.

IP Addresses and Java


Java has a class java.net.InetAddress which encapsulate
numerical/domain name of IP addresses.
InetAddress class can:
Performs name lookup (converting a host name into an IPaddress).
Performs reverse lookup (converting the address into a hostname).
InetAddress class has no visible constructor.
To create InetAddress object, you have to use one its available methods.
Some useful methods: InetAddress

public String getHostName() : Return the host name (e.g.: “www.sun.com”) of IP address.
String getHostAddress() :Returns string format of the address (e.g.: “192.18.97.241”)
InetAddress[] getAllByName(String hostName)
boolean equals(Object obj)
byte[] getByAddress() returns the IP address in byte format (as opposed to dotted decimal notation)
InetAddress getByName(String hostName)
InetAddress getLocalHost() returns the instance of InetAddresscontaining local host name and
address.

Output:

y Naol G.(MSc.)
Service Ports

⚫ Each service offered by a computer is uniquely identified by a port number.


Each Internet packet contains both the destination host address and the port
number on that host to which the message/request has to be delivered.
⚫ That is, IP address can be thought of as a house address when a letter is sent via
post/snail mail and port number as the name of a specific individual to whom
the letter has to be delivered.
⚫ Port numbers range from 0 to 65,535 (16-bit).Ports 0 - 1024 are called
well-known ports. They are reserved for use by well-known services:
⚫ 20, 21: FTP
⚫ 23:TELNET
⚫ 25: SMTP
⚫ 110: POP3
⚫ 80: HTTP
What is a Socket ?
A socket is an endpoint of a two-way communication link between two programs running
on the network. Network communication using Sockets is very much similar to performing
file I/O. In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O.
Socket-based communication is independent of a programming language used for
implementing it.
That means, a socket program written in Java language can communicate to a program
written in non-Java (say C or C++) socket program.

Types of socket in java:

A) Stream sockets enable a process to establish a connection with another process. While
the connection is in place, data flows between the processes in continuous streams.

Stream sockets provide a connection-oriented service. The protocol used for transmission is
the popular TCP (Transmission Control Protocol). Provides reliable , in-order byte-stream
service

B) Datagram sockets transmit individual packets of information.

This is typically not appropriate for use by everyday programmers because the transmission
protocol is UDP (User Datagram Protocol).UDP provides a connectionless service. A connectionless
service does not guarantee that packets arrive at the destination in any particular order.
The java.net package provides support for the two commonnetwork protocols:
TCP communication:
Socket
ServerSocket
UDP communication:
DatagramPacket
DatagramSocket
MulticastSocket

Socket Programming with TCP


TCP (Transmission Control Protocol)
A connection-oriented protocol.
Allows reliable communication between two applications.
Usually used over the Internet with IP as TCP/IP
Be similar to making a telephone call
The person placing the telephone call – client
The person waiting for a call – server
The java.net.ServerSocket and java.net.Socket classes are the only two classes you will
probably ever need to create a TCP/IP connection between two computers.

Sockets and Java Socket Classes


A program can read from a socket or write to a socket assimply as reading from a file
or writing to a file.

A socket is bound to a port number so that the TCP layer canidentify the application that data
destined to be sent.

Java.net package provides two classes:


Socket – for implementing a client
ServerSocket– for implementing a server

Socket Communication
A server (program) runs on a specific computer and has asocket that is bound to a
specific port.
The server waits and listens to the socket for a client to make a connection request.
Client
server

If everything goes well, the server accepts the connection.


Upon acceptance, the server gets a new socket bounds to a different port. It needs a new
socket (consequently a different port number) so that it can continue to listen to the original
socket for connection requests while serving the connected client.

server
Client

There are four fundamental operations a socket performs. These are:


⚫ Connect to a remote machine
⚫ Send data
⚫ Receive data
⚫ Close the connection
The java.net.Socketclass allows you to perform all fourfundamental socket
operations
Socket class represents the socket that both the client and server use to communicate
with each other.
Connection is accomplished through the constructors.
Each Socket object is associated with exactly one remote host. Toconnect to a different
host, you must create a new Socket object.
Socket Programming with TCP

Server process must first be running (must have created a socket). Recall thatTCP is not
connectionless.

Client contacts the server by creating client-local socket specifying IP address and port
number of server process. ClientTCP establishes connection to server TCP.

When contacted by client, server TCP creates a new socketfor server process to
communicate with client.

Allows server to talk with multiple clients

Source port numbers used to distinguish clients

From application viewpoint: TCP provides reliable, in-order transfer of bytes (“pipe”)
between client and server.

Establishing a Simple Server Using Stream Sockets

Five steps to create a simple stream server in Java:

1. Open the Server Socket: Each client connection handled with a Socket
object. Server blocks until client connects.

ServerSocket server = new ServerSocket( PORT );


2. Wait for the Client Request.
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new
DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readUTF();
Send to client: os.writeUTF(“Hello\n”);
5. Close socket:
client.close();
Establishing a Simple Client Using Stream Sockets

Four steps to create a simple stream client in Java:

1. Create a Socket Object:


Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server: Receive
data from the server: String line = is.readUTF(); Send data
to the server: os.writeUTF(“Hello\n”);
4. Close the socket when done:
client.close();
Example: Java server using TCP
Example: Java client using TCP
Output: first you must run server program..

Step-1: run TCPServer first Step-2: then run


TCPClient

Step-3: finally check TCPServer after TCPClient connected:

Socket Programming with UDP

Datagram sockets transmit individual packets of information.

This is typically not appropriate for use by everyday programmers because the transmission
protocol is UDP (User Datagram Protocol).

UDP provides a connectionless service. A connectionless service does not guarantee that
packets arrive at the destination in any particular order.

With UDP, packets can be lost or duplicated. Significant extra programming is required
on the programmer’s part to deal with these problems.

UDP is most appropriate for network applications that do not require the error checking
and reliability of TCP.
Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.

The sender explicitly attaches the IP address and port of the destination toeach packet.
The server must extract the IP address and port of the sender from thereceived
packet.
From an application viewpoint, UDP provides unreliable transfer of groups ofbytes
(“datagrams”) between client and server.

The java.net.DatagramPacket class –a data container


The java.net.DatagramSocket class – a mechanism to send and receive
DatagramPackets.
Sender does not wait for acknowledgements
Arrival, arrival time & order is not guaranteed. o So
why use UDP if it unreliable?
wo reasons: speed and overhead.
Used when speed is essential, even in cost of reliability
e.g. Streaming Media, Games, Internet Telephony, etc

DatagramPacket

Data to be transferred is encapsulated in a unit called datagram.


And in Java, DatagramPacket represents a datagram.
We can create a DatagramPacket object by using one of the followingconstructors:
⚫ DatagramPacket(byte[] buf, int length)
⚫ DatagramPacket(byte[] buf, int length, InetAddress address, int port)

Note: the data must be in the form of an array of bytes.


The first constructor: create a DatagramPacket to be received.
The second constructor: creates a DatagramPacket to be sent.
So you need to specify the address and port number of the destination host.
The parameter length specifies the amount of data in the byte array to be used.

Steps to Receive a Datagram packet - UDP


1. Create an array of bytes large enough to hold the data of the incoming packet.
byte[] buffer = new byte[1024];
2. A DatagramPacket object is instantiated using the array of bytes.
DatagramPacket packet =new DatagramPacket(buffer, buffer.length);
3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost
address, if necessary) on the localhost the socket will bind to.
int port = 1234;
DatagramSocket socket = new DatagramSocket(port);
4. The receive() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object. This causes the thread to block until a datagram packet is received
or a time out occurs.

Steps to Send a Datagram packet - UDP

Create an array of bytes large enough to hold the data of the packet to be sent, and fill the
array with the data.

byte[] buffer = new byte[1024];


Create a new DatagramPacket object that contains the array of bytes, as well as theserver
name and port number of the recipient.
int port = 1234;
InetAddress host =InetAddress.getByName(“www.mysite.com");
DatagramPacket packet =new DatagramPacket(buffer, buffer.length, host,
port);
A DatagramSocket is instantiated, and it is specified which port (and specific localhost
address, if necessary) on the localhost the
socket will bind to.DatagramSocket socket
= new DatagramSocket();
The send() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object.
Questions
Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for
creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are
responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern


o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific classes into the
code. That means the code interacts solely with the resultant interface or abstract class, so that it will
work with any classes that implement that interface or that extends that abstract class.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.

UML for Factory Method Pattern


o We are going to create a Plan abstract class and concrete classes that extends the Plan abstract class.
A factory class GetPlanFactory is defined as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information
(DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get
the type of object it needs.
Questions

Q. 1. What is JavaScript ? How it works ? What are the features of JavaScript ?


Q. 2. What is the difference between Java and JavaScript ? Describe the strengths and weakness of
JavaScript.
Q. 3. What are scripting languages and why JavaScript is used ? Write a JavaScript function for validating
form data like mandatory fields and email field.
Q. 4. Explain the role of JavaScript to develop a web page. Write a JavaScript function to check a textbox
is either empty or not.
. Q. 5. Explain conditional statements used in JavaScript with example.
Q. 6. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript
with example.
Q. 7. What is AJAX ? Explain its advantage and its working. Explain with example.
Q. 8. What is AJAX ? Explain the application of AJAX with the help of suitable examples.
Q. 9. Explain TCP/IP client socket. Also, write the constructor and methods used to create a client socket.
Q. 10. What is datagram ? Give its characteristics. Also, explain datagram socket.

You might also like