Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java

javascript notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java

javascript notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit -3

JavaScript

JavaScript is a cross-platform, object-oriented scripting language used to make webpages


interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are
also more advanced server side versions of JavaScript such as Node.js, which allow you to add
more functionality to a website than downloading files (such as realtime collaboration between
multiple computers). Inside a host environment (for example, a web browser), JavaScript can be
connected to the objects of its environment to provide programmatic control over them.

When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger brother” of
Java would help.

But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript, and now it has no relation to Java at all.

Today, JavaScript can execute not only in the browser, but also on the server, or actually on any
device that has a special program called the JavaScript engine.

The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

Different engines have different “codenames”. For example:

 V8 – in Chrome, Opera and Edge.


 SpiderMonkey – in Firefox.
 …There are other codenames like “Chakra” for IE, “JavaScriptCore”, “Nitro” and
“SquirrelFish” for Safari, etc.

There are at least three great things about JavaScript:

 Full integration with HTML/CSS.


 Simple things are done simply.
 Supported by all major browsers and enabled by default.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of
language elements such as operators, control structures, and statements. Core JavaScript can be
extended for a variety of purposes by supplementing it with additional objects; for example:

 Client-side JavaScript extends the core language by supplying objects to control a


browser and its Document Object Model (DOM). For example, client-side extensions
allow an application to place elements on an HTML form and respond to user events such
as mouse clicks, form input, and page navigation.
 Server-side JavaScript extends the core language by supplying objects relevant to
running JavaScript on a server. For example, server-side extensions allow an application
to communicate with a database, provide continuity of information from one invocation
to another of the application, or perform file manipulations on a server.

a property of an object is the value associated with the object. The property is accessed
by using the following notation:
objectName.propertyName

Document Object Model

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

1. window.document

Is same as

1. document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."
Properties of document object

Let's see the properties of document object that can be accessed and modified by the document
object.

Methods of document object

We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description
write("string") writes the given string on the doucment.
writes the given string on the doucment with newline character at
writeln("string")
the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object

In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>

<script type="text/javascript">

function getcube(){

var number=document.getElementById("number").value;

alert(number*number*number);

</script>

<form>
Enter No:<input type="text" id="number" name="number"/><br/>

<input type="button" value="cube" onclick="getcube()"/>

</form>

Login Form

html>
<head>
<title> Login Form</title>
</head>
<body>
<h3> LOGIN </h3>
<formform ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
<script type="text/javascript">
function submit_form(){
alert("Login successfully");
}
function create(){
window.location="signup.html";
}
</script>
</body>
</html>

Signup form

<html>

<head>

<title> SignUp Page</title>

</head>

<body align="center" >


<h1> CREATE YOUR ACCOUNT</h1>

<table cellspacing="2" align="center" cellpadding="8" border="0">

<tr><td> Name</td>

<td><input type="text" placeholder="Enter your name" id="n1"></td></tr>

<tr><td>Email </td>

<td><input type="text" placeholder="Enter your email id" id="e1"></td></tr>

<tr><td> Set Password</td>

<td><input type="password" placeholder="Set a password" id="p1"></td></tr>

<tr><td>Confirm Password</td>

<td><input type="password" placeholder="Confirm your password" id="p2"></td></tr>

<tr><td>

<input type="submit" value="Create" onClick="create_account()"/>

</table>

<script type="text/javascript">

function create_account(){

var n=document.getElementById("n1").value;

var e=document.getElementById("e1").value;

var p=document.getElementById("p1").value;

var cp=document.getElementById("p2").value;

//Code for password validation

var letters = /^[A-Za-z]+$/;

var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

//other validations required code


if(n==''||e==''||p==''||cp==''){

alert("Enter each details correctly");

else if(!letters.test(n))

alert('Name is incorrect must contain alphabets only');

else if (!email_val.test(e))

alert('Invalid email format please enter valid email id');

else if(p!=cp)

alert("Passwords not matching");

else if(document.getElementById("p1").value.length > 12)

alert("Password maximum length is 12");

else if(document.getElementById("p1").value.length < 6)

alert("Password minimum length is 6");

}
else{

alert("Your account has been created successfully... Redirecting to JavaTpoint.com");

window.location="https://www.google.com/";

</script>

</body>

</html>

JavaScript Statements

JavaScript statements are the set of keywords that commands the browser to perform the desired
action. Javascript statements are used to control the program flow. A Javascript program is made
up of statements. The order of execution of Statements is the same as they are written.

Semicolons
Semicolons separate JavaScript statements. A semicolon marks the end of a statement in
javascript.
{
let a, b, c;
a = 13;
b = 2;
c = a - b;
console.log("The value of c is " + c + ".");
}

JavaScript Code Blocks


JavaScript statements can be grouped together inside curly brackets. Such groups are known as
code blocks. The purpose of grouping is to define statements to be executed together. One place
you will find statements grouped together in blocks, is in JavaScript functions.
{
function fun1() {
console.log("Hello");
}
}
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable. The following lines are equivalent:
{
let person = "Alice";
let person="Alice";
}

JavaScript Line Length and Line Breaks


Breaking long JavaScript statements after operators is a common practice for improving code
readability. It helps maintain a reasonable line length, typically around 80-100 characters.
{
document.getElementById("hello").innerHTML =
"Hello World!";
}
JavaScript Keywords
Keywords are reserved words and cannot be used as a variable name. A Javascript keyword tells
about what kind of operation it will perform. List of some keywords:

Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop

Declarations of Statements

Javascript statements are declared by their syntax. The keywords are arranged in a syntactical
manner to be read by the translator. The Javascript statements are separated by semicolons (;).
A Javascript statement can be written in multiple lines as well and a single line can have multiple
Javascript statements.

Note: Javascript provides several types of statements like block, break, and return to perform
different operations. In the further sections, we will go through each of the statements with an
example.

Statements and Declarations by Category


Javascript statements are broadly divided into the following five categories:

Control Flow
Control flow refers to the order in which the instructions would be executed in the program.
Block
The block statement in Javascript is used to group a set of statements. The block statement in
Javascript is declared by a pair of braces (or curly brackets).
Declaration:
{
// This is a block in javascript
}

Break
The break statement in Javascript is used to stop the flow of a program. The break statement is
often used with loops (loops are discussed later in the article) to terminate their execution once a
particular condition is met.
Declaration:
break;

Continue
The continue statement in Javascript is often used to skip the iteration in a loop. When the
program encounters the continue statement while executing the loop, it skips the rest of the
statements in the block and jumps to the next iteration.
Declaration:
continue;

Empty
An empty statement in Javascript is used to layout no statement, i.e., it indicates that no
statement will be executed. It is represented by a semicolon.
Declaration
;

If...else
The if..else statements in Javascript are conditional statements that are used to execute the if
code block when the specified condition holds true otherwise, the else block gets executed.
Declaration:
if(condition){
//code
}else{
//code
}

Switch
The switch statement in Javascript is used to compare an expression with one or more cases. The
switch statement executes the statement associated with the case that holds true for the given
expression.
Declaration:
switch(expression){
case condition1 :
//code
break;

case condition2 :
//code
break;

case condition3 :
//code
break;

default:
//code
}

Throw
The throw statement in Javascript is used to throw customized errors. The program, upon
encountering the throw statement, ceases the program execution and jumps to the try-catch
block(If the try-catch block is not present, the program terminates).
Declaration:
throw expression;
try...catch
The try..catch statement in Javascript is used to execute statements with possibilities of error. It
is an error-handling approach in Javascript. The try statement defines the code block to be
executed, and the catch statement is used to handle the error during the execution of the code
block.
try{
//code
}catch (err){
//code
}

Declaring Variables
The declaration statement in Javascript is used to assign a value to a variable name. There are 3
ways to write declaration statements in Javascript:
Var
The Javascript statement var is used to declare a variable. The var statement declares a variable
globally, and the variable values can be updated or deleted.
Note: The var statement should be used carefully because if a variable is defined in a loop or in
an if statement using var, it can be accessed outside the block and accidentally redefined which
may lead to a buggy program.
Declaration:
var example;

Let
The Javascript statement let is also used to declare a variable. It was introduced to tackle the
buggy nature of the var. The let statement declares a variable in the block scope and the variable
values can be updated or deleted.
Declaration:
let example;

Const
The Javascript statement const is used to declare a constant value. The const statement declares a
value in the block scope and the values can not be updated or deleted.
Declaration:
const example;

Functions and Classes

Function
The Javascript statement function is used to define a block of code to perform specific tasks. The
function statement is often defined with parameters, though the choice of using parameters is
optional.
Declaration:
function fname(parameters){
//code
}

Function
The Javascript statement Generator Functions are special functions that can be paused to return a
value. The generator functions can be exited and later re-entered. These are used to write
iterators more effectively.
Note: Iterator in JavaScript is an object that is used to define a sequence and could return value a
sequence of values upon its termination
Declaration:
function* fname(parameters){
//code
}

Async function
The Javascript async function aids us to write promises, and it makes sure that the promise is
returned. In case of any error, unlike regular functions that terminate the execution, the async
function automatically gets wrapped in a promise that is resolved with its value.
The Javascript statement async function is used to declare an async function. The async function
statement is often defined with parameters, though the choice of using a parameter is optional.
Declaration:
async function fname(parameters){
//code
}

return
The Javascript statement return is used to stop the execution of a function and return a specified
value.
The return is important to get a response from the function. For e.g., imagine we have a function
to add two numbers. The function would take two numbers (as parameters) and store the sum in
a third variable. Although the sum operation is performed, to get the sum, we need to return that
variable.
Declaration:
function fname(parameters){
//code

return returnValue;
}
Class
The Javascript statement class is used to declare a class in javascript.
class in javascript is a template used to create an object. They act as a blueprint with methods
and parameters to create multiple objects of the same kind.
Declaration:
class cname [extends oName] {
// class body
}

Iterations
Iteration in Javascript is basically the process of going through the elements of a container. It is
mostly used when there is a need to access the elements of a container (e.g. an array).
do...while
The Javascript statement do...while is used to create a loop that first executes a particular
statement (the do block). Once the do-block is executed, it jumps to the while block. If the
condition of the while block is true, is again executes the do-block, otherwise, the loop
terminates.
Declaration:
do{
// statement
}
while (condition);

For
The Javascript statement for creates a loop that consists of three expressions, the initialization,
the condition, and the final-expression. The loop stops executing when the condition becomes
false.
Declaration:
for (initialization; condition; final-expression)
{
// statement
}

for...in
The Javascript statement for...in is used to loop through the enumerable properties of an object
that are keyed by string. The iteration over enumerable objects happens in random order.
Declaration:
for (variable in object) {
// statement
}

for...of
The Javascript statement for...of is used to adjure a custom iteration with the statements to be
executed. The for...of statement can be used to loop through the values of iterable objects. It lets
us iterate over data structures like arrays, array-like objects, etc.

Declaration:
for (variable of iterable) {
// statement
}

For await...of
The javascript statement for await...of is used to adjure a custom iteration with the statements to
be executed. The for await...of statement can be used to loop through async iterable objects as
well as through sync iterable objects.
Declaration:
for await (const variable of iterable) {
// statement
}

While
The Javascript statement while is used to create a loop that executes a code block till the
condition passed to it holds true. If the condition is false, the loop terminates.
Declaration:
while (condition){
//statement
}

Others:

Debugger
The javascript statement debugger is used to trigger the debugging functionalities available in the
program. In case there are no debugging functionalities present, this statement remains
inadequate.
Note: Debugging is the process of finding and eliminating bugs and possible errors in order to
achieve an error-free program.
Declaration:
debugger;

Export
A module in JavaScript is a file containing one or more units of code. Modules are mainly used
to group functions or object definitions together in order to make the code more structured and
manageable.
The Javascript statement export is used to export objects, variables, or functions so that is can be
accessed by external modules or other scripts.
Declaration:
export exportModule;

Import
The Javascript statement import is used to import the variables, functions, or objects that are
exported from a module or other scripts.

Declaration:
import importModule;

Import.meta
The Javascript statement import.meta provides information about the environment in which the
module runs. It is used to expose context-specific metadata to a JavaScript module.
Declaration:
import.meta;

Label
The Javascript statement label is an identifier followed by a colon (:), often applied to a code
block. It is used to define a statement with an identifier which can be used along with a continue
or break statement.
Declaration:
label :
statement

With
The Javascript statement with is used to extend the scope of an object. When the javascript
statements are being evaluated, the with statement adds the given statement to the head of the
scope chain.
The with statement is used to specify the default object, so we can use the properties inside of
that object without the dot notation.
Note: The with statement is not recommended, as it may be the source of confusing bugs and
compatibility issues.
Declaration:
with (expression){
// statement
}
JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save 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.

function functionName([arg1, arg2, ...argN]){

//code to be executed

Example:

<script>

function msg(){

alert("hello! this is message");

</script>

<input type="button" onclick="msg()" value="call function"/>

JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It


executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods

Let's see function methods with description.

Method Description
apply() It is used to call a function contains this value and a single array of arguments.
bind() It is used to create a new function.
call() It is used to call a function contains this value and an argument list.
toString() It returns the result in a form of a string.

Example:

<script>

var add=new Function("num1","num2","return num1+num2");

document.writeln(add(2,5));

</script>

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
4. Create an object using Object.create().
By object literal

Syntax:

object={property1:value1,property2:value2.....propertyN:valueN}

Example:
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

By creating instance of Object directly (using new keyword):

Syntax:

var objectname=new Object();

Example:
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

By using an object constructor (using new keyword)

Syntax:

Each argument value can be assigned in the current object by using this keyword.

The 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,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>

Ajax
Asynchronous JavaScript and XML (Ajax) refer to a group of technologies that are used to
develop web applications. By combining these technologies, web pages appear more responsive
since small packets of data are exchanged with the server and web pages are not reloaded each
time that a user makes an input change. Ajax enables a web application user to interact with a
web page without the interruption of constant web page reloading. Website interaction happens
quickly with only portions of the page reloading and refreshing.
Ajax is made up of the following technologies:

 XHTML and CSS for presenting information.


 Document Object Model (DOM) for dynamically interacting with and displaying the
presented information.
 XMLHttpRequest object to manipulate data asynchronously with the web server.
 XML, HTML, and XSLT for data interchange and manipulation.
 JavaScript for binding data requests and information display.

Ajax incorporates these technologies to create a new approach to developing web applications.

Ajax defines a method of initiating client to server communication without page reloads. It
provides a way to enable partial page updates. From a web page user perspective, it means
improved interaction with a web application, which gives the user more control of their
environment, similar to that of a desktop application.

In a traditional web application, HTTP requests, that are initiated by the user's interaction with
the web interface, are made to a web server. The web server processes the request and returns an
HTML page to the client. During HTTP transport, the user is unable to interact with the web
application.

In an Ajax web application, the user is not interrupted in interactions with the web application.
The Ajax engine or JavaScript interpreter enables the user to interact with the web application
independent of HTTP transport to and from the server by rendering the interface and handling
communications with the server on the user's behalf.

Ajax limitations
While Ajax is a web application development technique that is designed to make web pages
more responsive and interactive with a user, Ajax has some limitations to consider before you
develop an Ajax-based application. The following limitations are some of the more prominent
disadvantages:

 Browser support - Not all browsers support JavaScript or XMLHttpRequest object.


Even among browsers that do have support for JavaScript and XMLHttpRequest, these
objects can be treated differently. Each browser's implementation of Ajax must be
considered.
 Security and user privacy - Not all concerns are addressed. Issues surrounding security
and user privacy need to be considered when developing an Ajax application.
 Accessibility - Because not all browsers have JavaScript or XMLHttpRequest object
support, you must ensure that you provide a way to make the web application accessible
to all users.
 Bookmark and navigation - Since Ajax is used to asynchronously load bits of content
into an existing page, some of the page information may not correspond to a newly
loaded page. Browser history and bookmarks may not have the correct behavior since the
URL was unchanged despite parts of the page being changed.
 Search engine - Ajax applications are not searchable; however, it is possible to use Ajax
features and elements within an application that is searchable.

<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){
var val=request.responseText;
document.getElementById('amit').innerHTML=val;
}
}

</script>
</head>
<body>
<marquee><h1>This is an example of ajax</h1></marquee>
<form name="vinform">
<input type="text" name="t1">
<input type="button" value="ShowTable" onClick="sendInfo()">
</form>

<span id="amit"> </span>

</body>
</html>

create server side page to process the request


In this jsp page, we printing the table of given number.
index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));

for(int i=1;i<=10;i++)
out.print(i*n+"<br>");

%>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>table1.html</welcome-file>
</welcome-file-list>
</web-app>
Java InetAddress class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.

An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress


represents the IP address with its corresponding host name. There are two types of addresses:
Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.

Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.

IP Address
An IP address helps to identify a specific resource on the network using a numerical
representation.

 Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual
bridge among the destination and the source.

There are two versions of IP address:

1. IPv4

IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the
ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an
addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is more than 4
million addresses.

Features of IPv4:

 It is a connectionless protocol.
 It utilizes less memory and the addresses can be remembered easily with the class based
addressing scheme.
 It also offers video conferencing and libraries.
2. IPv6

IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet
addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address
space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also
identified with a name IPng (Internet Protocol next generation).

Features of IPv6:

 It has a stateful and stateless both configurations.


 It provides support for quality of service (QoS).
 It has a hierarchical addressing and routing infrastructure.

TCP/IP Protocol
 TCP/IP is a communication protocol model used connect devices over a network via
internet.
 TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.
 The two main protocols used in this communication model are:
1. TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of
packets at sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct
and the message is forwarded correctly or not.

Java InetAddress Class Methods


Method Description
public static InetAddress getByName(String host) It returns the instance of InetAddress
throws UnknownHostException containing LocalHost IP and name.
public static InetAddress getLocalHost() throws It returns the instance of InetAdddress
UnknownHostException containing local host name and address.
public String getHostName() It returns the host name of the IP address.
public String getHostAddress() It returns the IP address in string format.

Example of Java InetAddress Class


Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com
website.
InetDemo.java

1. import java.io.*;
2. import java.net.*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=InetAddress.getByName("www.javatpoint.com");
7.
8. System.out.println("Host Name: "+ip.getHostName());
9. System.out.println("IP Address: "+ip.getHostAddress());
10. }catch(Exception e){System.out.println(e);}
11. }
12. }

Factory Method is a creational design pattern that provides an interface for creating objects in a
superclass, but allows subclasses to alter the type of objects that will be created.

Factory methods are merely a convention whereby static methods in a class return an instance of
that class. Three commonly used InetAddress factory methods are shown here:

a) static InetAddress getLocalHost( ) throws UnknownHostException

b) static InetAddress getByName(String hostName) throws UnknownHostException

c) static InetAddress[ ] getAllByName(String hostName) throwsUnknownHostException

Factory Method Description

a) getLocalHost():

The getLocalHost( ) method simply returns the InetAddress object that represents the local
host.
b) getByName():

The getByName( ) method returns an InetAddress for a host name passed to it. If these methods
are unable to resolve the host name, they throw an UnknownHostException.

c) getAllByName():

The getAllByName( ) factory method returns an array of InetAddresses that represent all of the
addresses that a particular name resolves to. It will also throw an UnknownHostException if it
can’t resolve the name to at least one address.

Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

Important methods

Method Description
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
returns the socket and establish a connection between server
1) public Socket accept()
and client.
2) public synchronized void
closes the server socket.
close()

Example of Java Socket Programming


Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.

1. ServerSocket ss=new ServerSocket(6666);


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

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.

1. Socket s=new Socket("localhost",6666);

Let's see a simple of Java socket programming where client sends a text and server receives and
prints it.

File: MyServer.java

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

File: MyClient.java

1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Example of Java Socket Programming (Read-Write both


side)
1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}

File: MyClient.java

1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}

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:http// www.google.com/java networking

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.google.com is the server name.
3. Port Number: It is an optional attribute. If we write http// www.google.com:80/, 80 is
the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
Constructors of Java URL class
URL(String spec)

Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)

Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)

Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)

Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)

Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)

Creates an instance of a URL by parsing the given spec with the specified handler within a given
context.

Commonly used methods of Java URL class


The java.net.URL class provides many methods. The important methods of URL class are given
below.

Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public String getAuthority() it returns the authority of the URL.
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.
public URLConnection it returns the instance of URLConnection i.e. associated
openConnection() with this URL.
public boolean equals(Object obj) it compares the URL with the given object.
public Object getContent() it returns the content of the URL.
public String getRef() it returns the anchor or reference of the URL.
public URI toURI() it returns a URI of the URL.

Example of Java URL class


1. //URLDemo.java
2. import java.net.*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.google.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. }

Java URLConnection Class


The Java URLConnection class represents a communication link between the URL and the
application. It can be used to read and write data to the specified resource referred by the URL.

 URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that
helps to find a resource on the World Wide Web (WWW).
 URL has two components:

1. The protocol required to access the resource.


2. The location of the resource.

Features of URLConnection class

1. URLConnection is an abstract class. The two subclasses HttpURLConnection and


JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any
resource referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we
can use it to read or write or get further information like content length, etc.

Constructors

Constructor Description
1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.

URLConnection Class Methods

Method Description
It adds a general request property
void addRequestProperty(String key, String value)
specified by a key-value pair
It opens a communications link to the
resource referenced by this URL, if such
void connect()
a connection has not already been
established.
It returns the value of the
boolean getAllowUserInteraction()
allowUserInteraction field for the object.
int getConnectionTimeout() It returns setting for connect timeout.
It retrieves the contents of the URL
Object getContent()
connection.
It retrieves the contents of the URL
Object getContent(Class[] classes)
connection.
It returns the value of the content-
String getContentEncoding()
encoding header field.
It returns the value of the content-length
int getContentLength()
header field.
It returns the value of the content-length
long getContentLengthLong()
header field as long.
It returns the value of the date header
String getContentType()
field.
It returns the value of the date header
long getDate()
field.
It returns the default value of the
static boolean getDefaultAllowUserInteraction()
allowUserInteraction field.
It returns the default value of an
boolean getDefaultUseCaches()
URLConnetion's useCaches flag.
It returns the value of the
boolean getDoInput()
URLConnection's doInput flag.
It returns the value of the
boolean getDoInput()
URLConnection's doOutput flag.
It returns the value of the expires header
long getExpiration()
files.
It loads the filename map from a data
static FileNameMap getFilenameMap()
file.
String getHeaderField(int n) It returns the value of nth header field
It returns the value of the named header
String getHeaderField(String name)
field.
It returns the value of the named field
long getHeaderFieldDate(String name, long Default)
parsed as a number.
It returns the value of the named field
int getHeaderFieldInt(String name, int Default)
parsed as a number.
String getHeaderFieldKey(int n) It returns the key for the nth header field.
It returns the value of the named field
long getHeaderFieldLong(String name, long Default)
parsed as a number.
It returns the unmodifiable Map of the
Map<String, List<String>> getHeaderFields()
header field.
It returns the value of the object's
long getIfModifiedSince()
ifModifiedSince field.
It returns an input stream that reads from
InputStream getInputStream()
the open condition.
It returns the value of the last-modified
long getLastModified()
header field.
It returns an output stream that writes to
OutputStream getOutputStream()
the connection.
It returns a permission object
representing the permission necessary to
Permission getPermission()
make the connection represented by the
object.
int getReadTimeout() It returns setting for read timeout.
It returns the value of the named general
Map<String, List<String>> getRequestProperties()
request property for the connection.
It returns the value of the
URL getURL()
URLConnection's URL field.
It returns the value of the
boolean getUseCaches()
URLConnection's useCaches field.
It tries to determine the content type of
Static String guessContentTypeFromName(String
an object, based on the specified file
fname)
component of a URL.
static String It tries to determine the type of an input
guessContentTypeFromStream(InputStream is) stream based on the characters at the
beginning of the input stream.
It sets the value of the
void setAllowUserInteraction(boolean
allowUserInteraction field of this
allowuserinteraction)
URLConnection.
static void It sets the ContentHandlerFactory of an
setContentHandlerFactory(ContentHandlerFactory fac) application.
It sets the default value of the
static void setDefaultAllowUserInteraction(boolean allowUserInteraction field for all future
defaultallowuserinteraction) URLConnection objects to the specified
value.
It sets the default value of the useCaches
void steDafaultUseCaches(boolean defaultusecaches)
field to the specified value.
It sets the value of the doInput field for
void setDoInput(boolean doinput) this URLConnection to the specified
value.
It sets the value of the doOutput field for
void setDoOutput(boolean dooutput) the URLConnection to the specified
value.

How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection class.

Syntax:

1. public URLConnection openConnection()throws IOException{}

Displaying Source Code of a Webpage by URLConnecton


Class
The URLConnection class provides many methods. We can display all the data of a webpage by
using the getInputStream() method. It returns all the data of the specified URL in the stream that
can be read and displayed.

Example of Java URLConnection Class

1. import java.io.*;
2. import java.net.*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7. URLConnection urlcon=url.openConnection();
8. InputStream stream=urlcon.getInputStream();
9. int i;
10. while((i=stream.read())!=-1){
11. System.out.print((char)i);
12. }
13. }catch(Exception e){System.out.println(e);}
14. }
15. }

Java HttpURLConnection class


The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.

By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such
as header information, status code, response code etc.

The java.net.HttpURLConnection is subclass of URLConnection class.

HttpURLConnection Class Constructor


Constructor Description
protected HttpURLConnection(URL u) It constructs the instance of HttpURLConnection class.

Java HttpURLConnection Methods


Method Description
It shows that other requests from the server are
void disconnect()
unlikely in the near future.
It returns the error stream if the connection failed but
InputStream getErrorStream()
the server sent useful data.
It returns a boolean value to check whether or not
Static boolean getFollowRedirects()
HTTP redirects should be automatically followed.
String getHeaderField(int n) It returns the value of nth header file.
long getHeaderFieldDate(String name, It returns the value of the named field parsed as a
long Default) date.
String getHeaderFieldKey(int n) It returns the key for the nth header file.
It returns the value of HttpURLConnection's instance
boolean getInstanceFollowRedirects()
FollowRedirects field.
It returns the SocketPermission object representing
Permission getPermission() the permission to connect to the destination host and
port.
String getRequestMethod() It gets the request method.
It gets the response code from an HTTP response
int getResponseCode()
message.
It gets the response message sent along with the
String getResponseMessage()
response code from a server.
The method is used to enable streaming of a HTTP
void setChunkedStreamingMode(int
request body without internal buffering, when the
chunklen)
content length is not known in advance.
The method is used to enable streaming of a HTTP
void setFixedLengthStreamingMode(int
request body without internal buffering, when the
contentlength)
content length is known in advance.
The method is used to enable streaming of a HTTP
void setFixedLengthStreamingMode(long
request body without internal buffering, when the
contentlength)
content length is not known in advance.
It sets whether HTTP redirects (requests with
static void setFollowRedirects(boolean
response code) should be automatically followed by
set)
HttpURLConnection class.
It sets whether HTTP redirects (requests with
void setInstanceFollowRedirects(boolean
response code) should be automatically followed by
followRedirects)
instance of HttpURLConnection class.
Sets the method for the URL request, one of: GET
void setRequestMethod(String method) POST HEAD OPTIONS PUT DELETE TRACE are
legal, subject to protocol restrictions.
abstract boolean usingProxy() It shows if the connection is going through a proxy.

How to get the object of HttpURLConnection class


The openConnection() method of URL class returns the object of URLConnection class.
Syntax:

1. public URLConnection openConnection()throws IOException{}

You can typecast it to HttpURLConnection type as given below.

1. URL url=new URL("http://www.javatpoint.com/java-tutorial");


2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();

Java HttpURLConnection Example


1. import java.io.*;
2. import java.net.*;
3. public class HttpURLConnectionDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7. HttpURLConnection huc=(HttpURLConnection)url.openConnection();
8. for(int i=1;i<=8;i++){
9. System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
10. }
11. huc.disconnect();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.

Datagram
Datagrams are collection of information sent from one device to another device via the
established network. When the datagram is sent to the targeted device, there is no assurance that
it will reach to the target device safely and completely. It may get damaged or lost in between.
Likewise, the receiving device also never know if the datagram received is damaged or not. The
UDP protocol is used to implement the datagrams in Java.

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. It is a mechanism used for transmitting datagram packets over network.`

A datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.

Commonly used Constructors of DatagramSocket class


 DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

Java DatagramSocket Class


Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void close() It closes the datagram socket.
void connect(InetAddress
It connects the socket to a remote address for the socket.
address, int port)
void disconnect() It disconnects the socket.
boolean getBroadcast() It tests if SO_BROADCAST is enabled.
DatagramChannel It returns the unique DatagramChannel object associated with
getChannel() the datagram socket.
InetAddress getInetAddress() It returns the address to where the socket is connected.
InetAddress getLocalAddress() It gets the local address to which the socket is connected.
It returns the port number on the local host to which the socket
int getLocalPort()
is bound.
SocketAddress
It returns the address of the endpoint the socket is bound to.
getLocalSocketAddress()
int getPort() It returns the port number to which the socket is connected.
It gets the value of the SO_RCVBUF option for this
int getReceiverBufferSize() DatagramSocket that is the buffer size used by the platform for
input on the DatagramSocket.
boolean isClosed() It returns the status of socket i.e. closed or not.
boolean isConnected() It returns the connection state of the socket.
void send(DatagramPacket p) It sends the datagram packet from the socket.
void receive(DatagramPacket
It receives the datagram packet from the socket.
p)
Java DatagramPacket Class
Java DatagramPacket is a message that can be sent or received. It is a data container. If you
send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class


 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor
is used to receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.

Java DatagramPacket Class Methods


Method Description
It returns the IP address of the machine to which the
1) InetAddress getAddress() datagram is being sent or from which the datagram was
received.
2) byte[] getData() It returns the data buffer.
It returns the length of the data to be sent or the length of
3) int getLength()
the data received.
It returns the offset of the data to be sent or the offset of
4) int getOffset()
the data received.
It returns the port number on the remote host to which
5) int getPort() the datagram is being sent or from which the datagram
was received.
It gets the SocketAddress (IP address + port number) of
6) SocketAddress getSocketAddress() the remote host that the packet is being sent to or is
coming from.
It sets the IP address of the machine to which the
7) void setAddress(InetAddress iaddr)
datagram is being sent.
8) void setData(byte[] buff) It sets the data buffer for the packet.
9) void setLength(int length) It sets the length of the packet.
It sets the port number on the remote host to which the
10) void setPort(int iport)
datagram is being sent.
11) void
It sets the SocketAddress (IP address + port number) of
setSocketAddress(SocketAddress
the remote host to which the datagram is being sent.
addr)

Example of Sending DatagramPacket by DatagramSocket

1. //DSender.java
2. import java.net.*;
3. public class DSender{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket();
6. String str = "Welcome java";
7. InetAddress ip = InetAddress.getByName("127.0.0.1");
8.
9. DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
10. ds.send(dp);
11. ds.close();
12. }
13. }

Example of Receiving DatagramPacket by DatagramSocket

1. //DReceiver.java
2. import java.net.*;
3. public class DReceiver{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket(3000);
6. byte[] buf = new byte[1024];
7. DatagramPacket dp = new DatagramPacket(buf, 1024);
8. ds.receive(dp);
9. String str = new String(dp.getData(), 0, dp.getLength());
10. System.out.println(str);
11. ds.close();
12. }
13. }

You might also like