Java
Java
JavaScript
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”.
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:
a property of an object is the value associated with the object. The property is accessed
by using the following notation:
objectName.propertyName
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.
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.
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.
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.
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/>
</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>
</head>
<tr><td> Name</td>
<tr><td>Email </td>
<tr><td>Confirm Password</td>
<tr><td>
</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;
else if(!letters.test(n))
else if (!email_val.test(e))
else if(p!=cp)
}
else{
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 + ".");
}
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.
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;
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.
//code to be executed
Example:
<script>
function msg(){
</script>
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
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>
document.writeln(add(2,5));
</script>
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>
Syntax:
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>
Syntax:
Each argument value can be assigned in the current object by using this keyword.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=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:
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:
<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>
</body>
</html>
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.
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.
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:
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.
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) 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.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
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()
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.
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.
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. }
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
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.
Creates an instance of a URL from the given protocol name, host name, and file name.
Creates an instance of a URL by parsing the given spec within a specified context.
Creates an instance of a URL by parsing the given spec with the specified handler within a given
context.
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.
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:
Constructors
Constructor Description
1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.
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.
Syntax:
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. }
By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such
as header information, status code, response code etc.
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.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.
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. }
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. }