75% found this document useful (4 votes)
1K views

Java Tpoint

Java is a widely used programming language and platform. It can be used to create desktop applications, web applications, enterprise applications, and mobile applications. Some key features of Java include being platform independent, secured, robust, portable, and able to create multi-threaded and distributed applications. A simple "Hello World" Java program only requires creating a class with a main method that uses System.out.println to display output.

Uploaded by

Trilok Mahaday
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
75% found this document useful (4 votes)
1K views

Java Tpoint

Java is a widely used programming language and platform. It can be used to create desktop applications, web applications, enterprise applications, and mobile applications. Some key features of Java include being platform independent, secured, robust, portable, and able to create multi-threaded and distributed applications. A simple "Hello World" Java program only requires creating a class with a main method that uses System.out.println to display output.

Uploaded by

Trilok Mahaday
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 259

Java technology is widely used currently.

Let's start learning of java from basic questions like what is


java, where it is used, what type of applications are created in java and why use java?

James Gosling

What is Java?
Java is a programming language and a platform.
Platform Any hardware or software environment in which a program runs, known as a platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used.
Some of them are as follows:
1.

Desktop Applications such as acrobat reader, media player, antivirus etc.

2.

Web Applications such as irctc.co.in, javatpoint.com etc.

3.

Enterprise Applications such as banking applications.

4.

Mobile

5.

Embedded System

6.

Smart Card

7.

Robotics

8.

Games etc.

Types of Java Applications


There are mainly 4 type of applications that can be created using java:

1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to
install on every machine such as media player, antivirus etc. AWT and Swing are used in java for
creating standalone applications.

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of
high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.

4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating
mobile applications.

History of Java
1.

Brief history of Java

2.

Java Version History

Java history is interesting to know. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
At that time, it was a advanced concept for the green team. But, it was good for internet
programming. Later, Netscape Navigator incorporated Java technology.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
Let's see the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.

5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why they choosed java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).

Java Version History


There are many java versions that has been released.
1.

JDK Alpha and Beta (1995)

2.

JDK 1.0 (23rd Jan, 1996)

3.

JDK 1.1 (19th Feb, 1997)

4.

J2SE 1.2 (8th Dec, 1998)

5.

J2SE 1.3 (8th May, 2000)

6.

J2SE 1.4 (6th Feb, 2002)

7.

J2SE 5.0 (30th Sep, 2004)

8.

Java SE 6 (11th Dec, 2006)

9.

Java SE 7 (28th July, 2011)

There is given many features of java. They are also known as java buzzwords.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides softwarebased platform. The Java platform differs from most other platforms in the sense that it's
a software-based platform that runs on top of other hardware-based platforms.It has
two components:
1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc.


Java code is compiled by the compiler and converted into bytecode.This bytecode is a

platform independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).

Secured
Java is secured because:

No explicit pointer

Programs run inside virtual machine sandbox.

Classloader- adds security by separating the package for the classes of the local
file system from those that are imported from network sources.

Bytecode Verifier- checks the code fragments for illegal code that can violate
access right to objects.

Security Manager- determines what resources a class can access such as


reading and writing to the local disk.

These security are provided by java language. Some security can also be provided by
application developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine
on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it shares the same memory. Threads are important for multi-media,
Web applications etc.

Simple Program of Java


1.

We will learn how to write the hello java program. We can write a simple hello java program
easily.
Here, we have created a class named Simple that contains only main method which prints a
message hello java.

Requirement for Hello Java Example


For executing any java program, you need to

install the JDK if you don't have installed it, download the JDK and install it.

set path of the jdk/bin directory.

create the java program

compile and run the java program

Creating hello java example


Let's create the hello java program:
1. class Simple{
2.

public static void main(String args[]){

3.

System.out.println("Hello Java");

4.

5. }

save this file as Simple.java

To compile:

javac Simple.java

To execute:

java Simple

Output:Hello Java

Understanding first java program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility, it means it is


visible to all.

static is a keyword, if we declare any method as static, it is known as static


method. The core advantage of static method is that there is no need to
create object to invoke the static method. The main method is executed by
the JVM, so it doesn't require to create object to invoke the main method. So
it saves memory.

void is the return type of the method, it means it doesn't return any value.

main represents startup of the program.

String[] args is used for command line argument. We will learn it later.

System.out.println() is used print statement. We will learn about the


internal working of System.out.println statement later.

How many ways, we can write a java program?


There are many ways to write a java program. The modifications that can be done in a java
program are given below:
1)By changing sequence of the modifiers, method prototype is not changed.
Let's see the simple code of main method.
1. static public void main(String args[])
2)subscript notation in java array can be used after type, before variable or after variable.
Let's see the different codes to write the main method.
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
3)You can provide var-args support to main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in main method. We will learn about var-args later in
Java New Features chapter.
1. public static void main(String... args)
4)Having semicolon at the end of class in java is optional.
Let's see the simple code.

class A{
static public void main(String... args){
System.out.println("hello java4");
}
};

Internal Details of Hello Java Program


1. Internal Details of Hello Java

In the previous page, we have learned about the first program, how to compile and how to run
the first java program. Here, we are going to learn, what happens while compiling and running
the java program. Moreover, we will see some question based on the first program.
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
Interpreter: read bytecode stream then execute the instructions.

Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:

To compile:

javac Hard.java

To execute:

java Simple

Q)Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:

How to set path of JDK in Windows:


Path is required for using tools such as javac, java etc. If you are saving the java file
in jdk/bin folder, path is not required.But If you are having your java file outside the
jdk/bin folder, it is necessary to set path of JDK. There are two ways to set path of
JDK:
1. temporary

2. permanent
1)Setting temporary Path of JDK in Windows:
For setting the temporary path of JDK, you need to follow these steps:

Open command prompt

copy the path of bin folder

write in command prompt: set path=copiedpath

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

2)Setting Permanent Path of JDK in Windows:


For setting the permanent path of JDK, you need to follow these steps:

Go to MyComputer properties -> advanced tab -> environment variables ->


new tab of user variable -> write path in variable name -> write path of bin
folder in variable value -> ok -> ok -> ok

For Example:
1)Go to MyComputer properties
2)click on advanced tab
3)click on environment variables
4)click on new tab of user variables
5)write path in variable name

6)Copy the path of bin folder


7)paste path of bin folder in variable value
8)click on ok button
9)click on ok button
Now your permanent path is set.You can now execute any program of java from any
drive.
Setting Path in Linux OS
Setting the path in Linux OS is same as setting the path in the Windows OS. But
here we use export tool rather than set. Let's see how to set path in Linux OS:

export PATH=$PATH:/home/jdk1.6.01/bin/

Here, we have installed the JDK in the home directory under Root (/home).

Difference between JDK,JRE and JVM

Understanding the difference between JDK, JRE and JVM is important in Java. We will
have brief overview of JVM here. If you want to gain the detailed knowledge of JVM,
move to the next page. Firstly, let's see the basic differences between the JDK, JRE
and JVM.

JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

JVM
JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
The JVM performs four main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).

The JVM performs four main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory
area, execution engine etc.

1) Classloader:

Classloader is a subsystem of JVM that is used to load class files.


2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field and

method data, the code for methods.


3) Heap:

It is the runtime data area in which objects are allocated.


4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part
in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when
its method invocation completes.
5) Program Counter Regiser:

PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:

It contains all the native methods used in the application.


7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation.Here the term ?compiler? refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

Variable and Datatype in Java


In this page, we will learn about the variable and java data types. Variable is a
name of memory location. There are three types of variables: local, instance and
static. There are two types of datatypes in java, primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory.

int data=50;//Here data is variable

Types of Variable
There are three types of variables in java

local variable

instance variable

static variable

Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called

instance variable . It is not declared as static.


Static variable
A variable that is declared as static is called static variable. It cannot be local.

We will have detailed learning of these variables in next chapters.


Example to understand the types of variables
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Data Types in Java


In java, there are two types of data types

primitive data types

non-primitive data types

System.out.println("Factorial of 5="+result);
}

2) Program of fibonacci series.


class Fabnoci{
public static void main(String...args)
{
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}
}

3) Program of armstrong number.


class ArmStrong{
public static void main(String...args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
System.out.println("armstrong number");
else
System.out.println("it is not an armstrong number");
}

4) Program of checking palindrome number.


class Palindrome
{
public static void main( String...args)
{
int a=242;
int n=a,b=a,rev=0;
while(n>0)
{
a=n%10;

rev=rev*10+a;
n=n/10;

}
if(rev==b)
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}

5) Program of swapping two numbers without using third variable.


class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}

6) Program of factorial number by recursion


class FactRecursion{
static int fact(int n){
if(n==1)
return 1;
return n*=fact(n-1);
}
public static void main(String args[]){
int f=fact(5);
System.out.println(f);
}
}

Java OOPs Concepts

In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class

Collection of objects is called class. It is a logical entity.


Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as

inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Java OOPs Concepts


In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class

Collection of objects is called class. It is a logical entity.


Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction

Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as in Procedureoriented programming language it is not easy to manage if code grows as project
size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language
a global data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.

Java Naming convention


A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class,
package, variable, method, etc.), but it is not mandatory to follow that is why it is known as
convention not rule.
Advantage of java naming convention

By using standard Java naming conventions they make their code easier to read for themselves
and for other programmers. Readability of Java code is important because it means less time is
spent trying to figure out what the code does.

Name
class
name

Convention
should begin with uppercase letter and be a noun
e.g.String,System,Thread etc.

Interfac should begin with uppercase letter and be an adjective (whereever


e name possible). e.g. Runnable,ActionListener etc.
method should begin with lowercase letter and be a verb. e.g.
name
main(),print(),println(),actionPerformed() etc.
variable
should begin with lowercase letter e.g. firstName,orderNumber etc.
name
package
should be in lowercase letter. e.g. java,lang,sql,util etc.
name
should be in uppercase letter. e.g. RED,YELLOW,MAX_PRIORITY etc.

Object and Class in Java


constan
ts name

In this page, we will learn about the objects and classes. In object-oriented
programming, we design a program using objects and classes. Object is
the physical entity whereas class is the logical entity. A class works as a
template from which we create the objects.
Object

A runtime entity that has state and behaviour is known as an object. For example:
chair, table, pen etc. It can be tengible or intengible (physical or logical).
An object has three characterstics:

state:represents the data of an object.

behaviour:represents the behaviour of an object.

identity:Object identity is typically implemented via a unique ID.


The value of the ID is not visible to the external user, but is used
internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc.
known as its state. It is used to write, so writing is its behaviour.
Object is an instance of a class.Class is a template or blueprint from
which objects are created.So object is the instance(result) of a class.

Class
A class is a group of objects that have common property. It is a template or
blueprint from which objects are created.
A class in java can contain:

data member

method

constructor

block

Syntax to declare a class:


class <class_name>{
data member;
method;

}
Simple Example of Object and Class
In this example, we have created a Student class that have two data
members id and name. We are creating the object of the Student class by
new keyword and printing the objects value.
class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id+" "+s1.name);
}
}
Output:0 null

Instance variable
A variable that is created inside the class but outside the method, is
known as instance variable.Instance variable doesn't get memory at
compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an
object.
Advantage of Method

Code Reusability

Code Optimization

new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of


students
In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method
on it. Here, we are displaying the state (data) of the objects by invoking
the displayInformation method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}

void displayInformation(){System.out.println(rollno+"
"+name);}//method

public static void main(String args[]){


Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();
}
}
Output:111 Karan
222 Aryan

As you see in the above figure, object gets the memory in Heap area and
reference variable refers to the object allocated in the Heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle
class. Its exaplanation is same as in the above Student class example.
class Rectangle{
int length;
int width;
void insert(int l,int w){

length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

By new keyword

By newInstance() method

By clone() method

By factory method etc.

We will learn, these ways to create the object later.

Annonymous object
Annonymous simply means nameless.An object that have no reference is
known as annonymous object.
If you have to use an object only once, annonymous object is a good
approach.
class Calculation{

void fact(int n){


int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
1. }
2. }
Output:Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of
primitives.
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two ob

jects
Let's see the example:

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two o
bjects

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So, we
perform method overloading to figure out the program quickly.

Advantage of method overloading?


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

In java, Methood Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no.


of arguments
In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.

10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
Output:30
40

2)Example of Method Overloading by changing data


type of argument
In this example, we have created two overloaded methods that differs in data type. The
first sum method receives two integer arguments and second sum method receives two
double arguments.

10.
11.

class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}

12.
13.
14.
15.
16.
17.
18.
19.

public static void main(String args[])


{

Calculation obj=new Calculation();


obj.sum(10.5,10.5);
obj.sum(20,20);

}
}
Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return type of
method?
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity. Let's see how ambiguity may occur:
because there was problem:

10.
11.
12.
13.
14.
15.
16.
17.
18.

class Calculation
{
int sum(int a,int b)
{
System.out.println(a+b);
}
double sum(int a,int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{

Calculation obj=new Calculation();


int result=obj.sum(20,20); //Compile Time Error

}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be
called

Can we overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by
method overloading. Let's see the simple example:
class Simple
{

public static void main(int a)


{

{
10.
11.
12.
13.

System.out.println(a);
}
public static void main(String args[])
System.out.println("main() method invoked");
main(10);
}

}
Output:main() method invoked
10

Method Overloading and TypePromotion


One type is promoted to another implicitly if no matching datatype is found. Let's
understand the concept by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion

class Calculation
{
void sum(int a,long b)
{System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
10.
11.
12.
13.
14.
15.
16.
17.
18.

public static void main(String args[])


{

Calculation obj=new Calculation();


obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);

}
}
Output:40
60

Example of Method Overloading with TypePromotion if


matching found
If there are matching type arguments in the method, type promotion is not performed.
class Calculation{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked

Example of Method Overloading with TypePromotion in


case ambiguity
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class Calculation
{
void sum(int a,long b)

10.
11.
12.
13.
14.
15.
16.
17.

{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{

Calculation obj=new Calculation();


obj.sum(20,20);//now ambiguity
}

}
Output:Compile Time Error

Constructor in Java
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor

1) Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1.

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Que)What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on
the type.

Example of default constructor that displays the default


values
class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
Output:0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor.Here 0 and null values are provided by default constructor.

Parameterized constructor
A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student{
int id;
String name;
Student(int i,String n)
{

id = i;
name = n;
}
void display()

{
System.out.println(id+" "+name);
}
public static void main(String args[])
{

Student s1 = new Student(111,"Karan");


Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}

}
Output:111 Karan
222 Aryan

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
by taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;

name = n;
}
Student(int i,String n,int a)
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[])


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}

Output:111 Karan 0
222 Aryan 25

What is the difference between constructor and method ?


There are many differences between constructors and methods. They are given below.
Constructor

Method

Constructor is used to initialize the state of an object.

Method is used to expose behaviour of


an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you


don't have any constructor.

Method is not provided by compiler in


any case.

Constructor name must be same as the class name.

Method name may or may not be same


as class name.

Copying the values of one object to another like copy constructor


in C++
There are many ways to copy the values of one object into another. They are:

By constructor

By assigning the values of one object into another

By clone() method of Object class

In this example, we are going to copy the values of one object into another using
constructor.
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
Student(Student s)
{

id = s.id;
name =s.name;
}
void display()

{
System.out.println(id+" "+name);
}
public static void main(String args[])
{

Student s1 = new Student(111,"Karan");


Student s2 = new Student(s1);
s1.display();
s2.display();
}

}
Output:111 Karan
111 Karan

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
class Student
{
int id;
String name;

Student(int i,String n)
id = i;
name = n;
}
Student()

{
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{

Student s1 = new Student(111,"Karan");


Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}

}
Output:111 Karan
111 Karan

Que)Does constructor return any value?


Ans:yes,that is current class instance (You cannot use return type yet it returns a
value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

static keyword
The static keyword is used in java mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to
the class than instance of the class.

The static can be:


1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) static variable
If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees,college name of
students etc.

The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1.
2.
3.
4.
5.

class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.

static property is shared to all objects.

Example of static variable


//Program of static variable
class Student
{
int rollno;
String name;
static String college ="ITS";

Student(int r,String n)
{

rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS

Program of counter without static variable


In this example, we have created an instance variable named count which is incremented in
the constructor. Since instance variable gets the memory at the time of object creation,

each object will have the copy of the instance variable, if it is incremented, it won't reflect to
other objects. So each objects will have the value 1 in the count variable.
class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}}
Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
class Counter
{
static int count=0;//will get memory only once and retain its value
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1

2
3

2) static method
If you apply static keyword with any method, it is known as static method

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).
class Student
{
int rollno;
String name;
static String college = "ITS";
{

static void change()


college = "BBDIT";
}
Student(int r, String n)

rollno = r;
name = n;
}

void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student.change();
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}

}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal


calculation
//Program to get cube of a given number by static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{

int result=Calculate.cube(5);
System.out.println(result);
}

}
Output:125

Restrictions for static method


There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
class A
{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Output:Compile Time Error

Que)why main method is static?


Ans) because object is not required to call static method if it were non-static method,
jvm create object first then call main() method that will lead the problem of extra

memory allocation.

3)static block

Is used to initialize the static data member.

It is executed before main method at the time of classloading.

Example of static block


class A{
static{System.out.println("static block is invoked");}

public static void main(String args[]){


System.out.println("Hello main");
}

Output:static block is invoked


Hello main

Que)Can we execute a program without main() method?


Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:static block is invoked (if not JDK7)

super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.

Usage of super Keyword


1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.

3. super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance variable.


Problem without super keyword
class Vehicle{
int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
} }

Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.
Solution by super keyword
//example of super keyword
class Vehicle{
int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
} Output:50

2 super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor as given
below:
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}
Output:Vehicle is created
Bike is created

super() is added in each class constructor automatically by compiler.

As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you
don't have either this() or super() as the first statement, compiler will provide super() as

the first statement of the constructor.

Another example of super keyword where super() is provided by the compiler


implicitly.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
int speed;
Bike(int speed){
this.speed=speed;
System.out.println(speed);
} public static void main(String args[]){
Bike b=new Bike(10);
}
}

Output:Vehicle is created
10

3) super can be used to invoke parent class method.


The super keyword can also be used to invoke parent class method. It should be used in
case subclass contains the same method as parent class as in the example given below:
class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}

Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class

not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class
does not have message() method, so you can directly call message() method.

Program in case super is not required


class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void display(){
message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}
Output:welcome

Instance initializer block:


Instance Initializer block is used to initialize the instance data member. It run each
time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed
extra operations while initializing the instance variable in the instance initializer block.

Que) What is the use of instance initializer block while we can directly assign a
value in instance data member? For example:

class Bike{
int speed=100;
}

Why use instance initializer block?


Suppose I have to perform some operations while assigning value to instance data
member e.g. a for loop to fill a complex array or error handling etc.

Example of instance initializer block


Let's see the simple example of instance initializer block the performs initialization.
class Bike{
int speed;
Bike(){System.out.println("speed is "+speed);}
{speed=100;}
public static void main(String args[]){
Bike b1=new Bike();
Bike b2=new Bike();
}
}
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block

What is invoked firstly instance initializer block or constructor?


class Bike{
int speed;
Bike(){System.out.println("constructor is invoked");}
{System.out.println("instance initializer block invoked");}
public static void main(String args[]){
Bike b1=new Bike();
Bike b2=new Bike();

}
}
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler
copies the instance initializer block in the constructor after the first statement super().
So firstly, constructor is invoked. Let's understand it by the figure given below:

Note: The java compiler copies the code of instance initializer block in every
constructor.

Rules for instance initializer block :

There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked
(i.e. after super() constructor call).
3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after super()


class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B extends A{
B(){
super();
System.out.println("child class constructor invoked");
}
{System.out.println("instance initializer block is invoked");}
public static void main(String args[]){
B b=new B();
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

Another example of instance block


class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B extends A{
B(){
super();
System.out.println("child class constructor invoked");
}
B(int a){
super();
System.out.println("child class constructor invoked "+a);
}

{
System.out.println("instance initializer block is invoked");
}
public static void main(String args[])
{
B b1=new B();
B b2=new B(10);
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10

Final Keyword In Java


The final keyword in java is used to restrict the user. The final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.

1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}//end of class
Output:Compile Time Error

2) final method
If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}

}
Output:Compile Time Error

3) final class
If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda extends Bike{
public static void main(String args[]){
new Honda().run();
}
}
Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.

Example of blank final variable


class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}

Que) Can we initialize blank final variable?


Yes, but only in constructor. For example:

class Bike
{
final int speedlimit;//blank final variable
{

Bike()
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[])

}
}

new Bike();

Output:70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.

Example of static blank final variable


class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

Q) What is final parameter?


If you declare any parameter as final, you cannot change the value of it.
class Bike{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike b=new Bike();
b.cube(5);
}
}
Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatchis a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

class A{}
class B extends A{}
A a=new B();//upcasting

Example of Runtime Polymorphism


In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference
variable of Parent class. Since it refers to the subclass object and subclass method overrides
the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}

}
Output:running safely with 60km.

Real example of Java Runtime Polymorphism


Consider a scenario, Bank is a class that provides method to get the rate of interest. But,
rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7% and 9% rate of interest.

Note: It is also given in method overriding but there was no upcasting.


class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){

Bank b1=new SBI();


Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Runtime Polymorphism with data member


Method is overridden not the datamembers, so runtime polymorphism can't be achieved
by data members.
In the example given below, both the classes have a datamember speedlimit, we are
accessing the datamember by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the datamember which is not overridden, hence
it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.


class Bike{
int speedlimit=90;
}
class Honda extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda();
System.out.println(obj.speedlimit);//90
}

Output:90

Runtime Polymorphism with Multilevel Inheritance


Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}

}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}

Output: eating
eating fruits
drinking Milk

Try for Output


class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog extends Dog{
public static void main(String args[]){
Animal a=new BabyDog();
a.eat();
}}
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

Static Binding and Dynamic Binding


Connecting a method call to the method body is known as binding.
There are two types of binding
1. static binding (also known as early binding).

2. dynamic binding (also known as late binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type


Each variable has a type, it may be primitive and non-primitive.
int data=30;
Here data variable is a type of int.

2) References have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.


class Animal{}
class Dog extends Animal{
public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.
If there is any private, final or static method in a class, there is static binding.

Example of static binding


class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();

d1.eat();
}
}

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the
instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its
base type.

instanceof operator
The instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with
any variable that have null value, it returns false.

Simple example of instanceof operator


Let's see the simple example of instance operator where it tests the current class.
class Simple
{
public static void main(String args[])
{
Simple s=new Simple();
System.out.println(s instanceof Simple);//true

}
}
Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.

Another example of instanceof operator


class Animal{}
class Dog extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog d=new Dog();
System.out.println(d instanceof Animal);//true
}
}
Output:true

instanceof operator with a variable that have null value


If we apply instanceof operator with a variable that have null value, it returns false. Let's
see the example given below where we apply instanceof operator with the variable that
have null value.
class Dog{
public static void main(String args[]){
Dog d=null;
System.out.println(d instanceof Dog);//false
}
}
Output:false

Downcasting with instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting. If we
perform it directly, compiler gives Compilation error. If you perform it by typecasting,
ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is
possible.
Dog d=new Animal();//Compilation error
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
Dog d=(Dog)new Animal();
//Compiles successfully but ClassCastException is thrown at runtime

Possibility of downcasting with instanceof operator


Let's see the example, where downcasting is possible by instanceof operator.
class Animal { }
class Dog extends Animal {
static void method(Animal a) {
if(a instanceof Dog){
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
}
10.
11.
12.
13.
14.
15.
16.

public static void main (String [] args) {


Animal a=new Dog();
Dog.method(a);
}
}
Output:ok downcasting performed

Downcasting without the use of instanceof operator


Downcasting can also be performed without the use of instanceof operator as displayed in
the following example:
class Animal { }
class Dog extends Animal {
static void method(Animal a) {
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Animal a=new Dog();
Dog.method(a);
10.
}
11.
}
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class.
So if we downcast it, it is fine. But what will happen if we write:
Animal a=new Animal();
Dog.method(a);
//Now ClassCastException but not in case of instanceof operator

Understanding Real use of instanceof operator

Let's see the real use of instanceof keyword by the example given below.
interface Printable{}
class A implements Printable{
public void a(){System.out.println("a method");}
}
class B implements Printable{
public void b(){System.out.println("b method");}
}
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.

class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
}
}
}//end of Call class
class Test{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}
Output: b method

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class. Before learning
abstract class, let's understand the abstraction first.

Abstraction
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction


There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.

Syntax to declare the abstract class


1.

abstract class <class_name>{}

abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.

Syntax to define the abstract method


1.

abstract return_type <method_name>();//no braces{}

Example of abstract class that have abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}
Output:running safely..

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the Rectangle
and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the
end user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about
the factory method later.
In this example, if you create the instance of Rectangle class, draw method of Rectangle
class will be invoked.
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}

Output:drawing circle

Abstract class having constructor, data member, methods etc.


Note: An abstract class can have data member, abstract method, method body,
constructor and even main() method.
//example of abstract class that have method body
abstract class Bike{
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();

obj.run();
obj.changeGear();
}
}
Output:running safely..
gear changed
//example of abstract class having constructor, field and method
abstract class Bike
{
int limit=30;
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}

Output:constructor is invoked
running safely..
it has two wheels
30

Rule: If there is any abstract method in a class, that class must be abstract.
class Bike{
abstract void run();
}
Output:compile time error

Rule: If you are extending any abstact class that have abstract method, you must either
provide the implementation of the method or make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();

void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Output:I am a
I am b
I am c
I am d

nterface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported

in case of class.
5. Marker Interface
6. Nested Interface
An interface is a blueprint of a class. It has static constants and abstract methods.

The interface is a mechanism to achieve fully abstraction in java. There can be only
abstract methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Interface?


There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public
and abstract.

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Simple example of Interface


In this example, Printable interface have only one method, its implementation is
provided in the A class.
interface printable{
void print();
}
class A implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

Q) Multiple inheritance is not supported in case of class but it is supported in


case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in
case of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
interface Printable{
void print();

}
interface Showable{
void print();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
Output:Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class A, so there is no ambiguity.

Note: A class implements interface but One interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class A implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

Que) What is marker or tagged interface ?


An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information

to the JVM so that JVM may perform some useful operation.


//How Serializable interface is written?
public interface Serializable{
}

Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}

Package in Java
A package is a group of similar types of classes, interfaces and sub-packages.
Package can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Package

Package is used to categorize the classes and interfaces so that they can be easily
maintained.

Package provids access protection.

Package removes naming collision.

Simple example of package


The package keyword is used to create a package.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile the Package (if not using IDE)


If you are not using any IDE, you need to follow the syntax given below:
1.

1.

javac -d directory javafilename


For example
javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).

How to run the Package (if not using IDE)


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack; import pack.*;


class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello

Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

Output:Hello

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage

Package inside the package is called the subpackage. It should be created to categorize
the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean


or org.sssit.dao.

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:
e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that

tells where to look for class file. For example:


e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

Temporary
o

By setting the classpath in the command prompt

By -classpath switch

Permanent
o

By setting the classpath in the environment variables

By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
//save as C.java otherwise Compilte Time Error
class A{}
class B{}
public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing
one public class, but keep the package name same. For example:
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}

Access Modifiers
1. private access modifier
2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifier with method overriding
There are two types of modifiers in java: access modifier and non-access modifier. The
access modifiers specifies accessibility (scope) of a datamember, method, constructor or
class.
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.

1) private
The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
1.
2.
3.
4.
5.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

6.
7.
8.
9.
10.
11.
12.

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor:


If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.

2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{

7.
8.

public static void main(String args[]){


A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.

3) protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Understanding all java access modifiers


Let's understand the access modifiers by a simple table.
Access Modifier

within class

within package

outside package by subclass only

outside package

Private

Default

Protected

Public

Applying access modifier with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not
be more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error

public static void main(String args[]){


Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why there is compile time
error.

Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g.
capsule i.e mixed of several medicines.
We can create a fully encapsulated class by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
Java Bean is the example of fully encapsulated class.

Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or writeonly.
It provides you the control over the data. Suppose you want to set the value of id i.e.
greater than 100 only, you can write the logic inside the setter method.

Simple example of encapsulation in java


Let's see the simple example of encapsulation that has only one field with its setter and
getter methods.
//save as Student.java
package com.javatpoint;
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//save as Test.java
package com.javatpoint;
class Test{
public static void main(String[] args){

Student s=new Student();


s.setname("vijay");
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay

Object class in Java


The Object class is the parent class of all the classes in java bydefault. In other words, it is
the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of
any type like Employee,Student etc, we can use Object class reference to refer that object.
For example:
1.

Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:
Method

Description

public final ClassgetClass()

returns the Class class object of this object. The


Class class can further be used to get the
metadata of this class.

public int hashCode()

returns the hashcode number for this object.

public boolean equals(Object obj)

compares the given object to this object.

protected Object clone() throws


CloneNotSupportedException

creates and returns the exact copy (clone) of this


object.

public String toString()

returns the string representation of this object.

public final void notify()

wakes up single thread, waiting on this object's


monitor.

public final void notifyAll()

wakes up all the threads, waiting on this object's


monitor.

public final void wait(long


timeout)throws InterruptedException

causes the current thread to wait for the specified


milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

public final void wait(long timeout,int


nanos)throws InterruptedException

causes the current thread to wait for the specified


miliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).

public final void wait()throws


InterruptedException

causes the current thread to wait, until another


thread notifies (invokes notify() or notifyAll()
method).

protected void finalize()throws


Throwable

is invoked by the garbage collector before object is


being garbage collected.

We will have the detailed learning of these methods in next chapters.

Object Cloning in Java


The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
1.

protected Object clone() throws CloneNotSupportedException

Why use clone() method ?


The clone() method saves the extra processing task for creating the exact copy of an
object. If we perform it by using the new keyword, it will take a lot of processing to be
performed that is why we use object cloning.

Advantage of Object cloning


Less processing task.

Example of clone()
method (Object cloning)
Let's see the simple example of object
cloning
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Output:101 amit
101 amit
As you can see in the above example, both reference variables have the same value. Thus,
the clone() copies the values of an object to another. So we don't need to write explicit code
to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this
one, it will require a lot of processing on this object. So to save the extra processing task we
use clone() method.

Array in Java
Normally, array is a collection of similar type of elements that have contiguous memory
location.
In java, array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.

Advantage of Array

Code Optimization: It makes


the code optimized, we can
retrieve or sort the data easily.

Random access: We can get any data located at any index position.

Disadvantage of Array

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.

Types of Array
There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array


Syntax to Declare an Array in java
dataType[] arrayRefVar; (or)
dataType []arrayRefVar; (or)
dataType arrayRefVar[];

Instantiation of an Array in java


arrayRefVar=new datatype[size];

Example of single dimensional java array


Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
class B{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output: 10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class B{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:33
3
4
5

Passing Java Array in the method


We can pass the array in the method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
class B{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array in the method
}}
Output:3

Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional java array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
class B{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:1 2 3
2 4 5
4 4 5

What is class name of java array?


In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.
class B{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}}
Output:I

Copying an array
We can copy an array to another by the arraycopy method of System class.Syntax

arraycopy method

public static void arraycopy(


Object src, int srcPos,Object dest, int destPos, int length
)

Example of arraycopy method

class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Output:caffein

Addition 2 matrices
Let's see a simple example that adds two matrices.
class AE{
public static void main(String args[]){
//creating two matrices

of

int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:2 6 8
6 8 10

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
download this example
Output:before change 50
after change 50

Another Example of call by value in java


In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed. In
this example we are passing object as a value. Let's take a simple example:
class Operation2{
int data=50;
void change(Operation2 op){
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[]){
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
download this example
Output:before change 50
after change 150

strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you
perform operations in the floating-point variable. The precision may differ from platform
to platform that is why java programming language have provided the strictfp keyword,
so that you get same result on every platform. So, now you have better control over the
floating-point arithmetic.

Legal code for strictfp keyword


The strictfp keyword can be applied on methods, classes and interfaces.
strictfp class A{}//strictfp applied on class
strictfp interface M{}//strictfp applied on interface
class A{
void m(){}//strictfp applied on method
}

Illegal code for strictfp keyword


The strictfp keyword can be applied on abstract methods, variables or constructors.
class B{
strictfp abstract void m();//Illegal combination of modifiers
}
class B{
strictfp int data=10;//modifier strictfp not allowed here
}
class B{
strictfp B(){}//modifier strictfp not allowed here
}

Creating API Document | javadoc tool


We can create document api in java by the help of javadoc tool. In the java file, we must
use the documentation comment /**... */ to post information for the class, method,
constructor, fields etc.
Let's see the simple class that contains documentation comment.
package com.abc;
/** This class is a user-defined class that contains one methods cube.*/
public class M{
/** The cube method prints cube of the given number */
public static void cube(int n){System.out.println(n*n*n);}
}
To create the document API, you need to use the javadoc tool followed by java file name.
There is no need to compile the javafile.
On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the
index.html file to get the information about the classes.

Java Command Line Arguments


The command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.

So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Example of command-line argument that prints all the


values
In this example, we are printing all the arguments passed from the command-line. For
this purpose, we have traversed the array using for loop.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

String Handling in Java


1. String Handling
2. How to create string objects?

1.

String literal

2.

new keyword

3. Why Java uses the concept of String literal?


String Handling provides a lot of concepts that can be performed on a string such as
concatenating string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later.
Let's first understand what is string and how we can create the string object.

String
Generally string is a sequence of characters. But in java, string is an object. String class is
used to create string object.

Do You Know ?

Why String objects are immutable ?

How to create an immutable class ?

What is string constant pool ?

What code is written by the compiler if you concat any string by + (string
concatenation operator) ?

What is the difference between StringBuffer and StringBuilder class ?

How to create String object?


There are two ways to create String object:
1. By string literal
2. By new keyword

1) String literal
String literal is created by double quote.For Example:
String s="Hello";

Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance returns. If the string
does not exist in the pool, a new String object instantiates, then is placed in the pool.For
example:
String s1="Welcome";
String s2="Welcome";//no new object will be created

In the above example only one object will be created.First time JVM will find no string
object with the name "Welcome" in string constant pool,so it will create a new
object.Second time it will find the string with the name "Welcome" in string constant
pool,so it will not create new object whether will return the reference to the same
instance.
Note: String objects are stored in a special memory area known as string constant
pool inside the Heap memory.

Why java uses concept of string literal?


To make Java more memory efficient (because no new objects are created if it exists
already in string constant pool).

2) By new keyword
1.

String s=new String("Welcome");//creates two objects and one reference variable


In such case, JVM will create a new String object in normal(nonpool) Heap memory and
the literal "Welcome" will be placed in the string constant pool.The variable s will refer to
the object in Heap(nonpool).

Immutable String in Java


In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
Let's try to understand the immutability concept by the example given below:
class Simple{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a
new object is created with sachintendulkar. That is why string is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
class Simple{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.

Why string objects are immutable in java?


Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the value of
the object, it will be affected to all the reference variables. That is why string objects are
immutable in java.

String comparison in Java


We can compare two given strings on the basis of content and reference.
It is used in authentication (by equals() method),sorting (by compareTo()
method), reference matching (by == operator) etc.
There are three ways to compare String objects:
1. By equals() method
2. By = = operator
3. By compareTo() method

1) By equals() method
equals() method compares the original content of the string.It compares values of string
for equality.String class provides two methods:

public boolean equals(Object another){} compares this string to the specified


object.

public boolean equalsIgnoreCase(String another){} compares this String to


another String, ignoring case.

class Simple{
public static void main(String args[]){
String
String
String
String

s1="Sachin";
s2="Sachin";
s3=new String("Sachin");
s4="Saurav";

System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false

}
Output:true
true
false
//Example of equalsIgnoreCase(String) method
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true

}
}
Output:false
true

2) By == operator
The = = operator compares references not values.
//<b><i>Example of == operator</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:true
false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:

s1 == s2 :0

s1 > s2

:positive value

s1 < s2

:negative value

//<b><i>Example of compareTo() method:</i></b>


class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:0
1
-1

String Concatenation in Java


Concating strings form a new string i.e. the combination of multiple strings.
There are two ways to concat string objects:
1. By + (string concatenation) operator
2. By concat() method

1) By + (string concatenation) operator


String concatenation operator is used to add strings.For Example:
//Example of string concatenation operator
class Simple{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar

}
}
Output:Sachin Tendulkar

The compiler transforms this to:


1.

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();


String concatenation is implemented through the StringBuilder(or StringBuffer) class and

its append method.String concatenation operator produces a new string by appending


the second operand onto the end of the first operand.The string concatenation operator
can concat not only string but primitive values also.For Example:
class Simple{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If
both operands are numbers, the operator will perform an addition.

2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
//<b><i>Example of concat(String) method</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar

Substring in Java

A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is
inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.

In case of string:

startIndex:starts from index 0(inclusive).

endIndex:starts from index 1(exclusive).

Example of java substring


//Example of substring() method
class Simple{
public static void main(String args[]){
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin

}
}
Output:Tendulkar
Sachin

Methods of String class in Java


java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting
strings etc.
Let's see the important methods of String class.
Method

Description

1)public boolean equals(Object anObject)

Compares this string to the specified object.

2)public boolean equalsIgnoreCase(String


another)

Compares this String to another String, ignoring


case.

3)public String concat(String str)

Concatenates the specified string to the end of


this string.

4)public int compareTo(String str)

Compares two strings and returns int

5)public int compareToIgnoreCase(String str)

Compares two strings, ignoring case differences.

6)public String substring(int beginIndex)

Returns a new string that is a substring of this


string.

7)public String substring(int beginIndex,int


endIndex)

Returns a new string that is a substring of this


string.

8)public String toUpperCase()

Converts all of the characters in this String to


upper case

9)public String toLowerCase()

Converts all of the characters in this String to


lower case.

10)public String trim()

Returns a copy of the string, with leading and


trailing whitespace omitted.

11)public boolean startsWith(String prefix)

Tests if this string starts with the specified


prefix.

12)public boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

13)public char charAt(int index)

Returns the char value at the specified index.

14)public int length()

Returns the length of this string.

15)public String intern()

Returns a canonical representation for the string


object.

16)public byte[] getBytes()

Converts string into byte array.

17)public char[] toCharArray()

Converts string into char array.

18)public static String valueOf(int i)

converts the int into String.

19)public static String valueOf(long i)

converts the long into String.

20)public static String valueOf(float i)

converts the float into String.

21)public static String valueOf(double i)

converts the double into String.

22)public static String valueOf(boolean i)

converts the boolean into String.

23)public static String valueOf(char i)

converts the char into String.

24)public static String valueOf(char[] i)

converts the char array into String.

25)public static String valueOf(Object obj)

converts the Object into String.

26)public void replaceAll(String firstString,String


secondString)

Changes the firstString with secondString.

First seven methods have already been discussed.Now Let's take the example of other
methods:

toUpperCase() and toLowerCase() method


class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
Output:SACHIN
sachin
Sachin

trim() method
class Simple{
public static void main(String args[]){
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
Output:Sachin
Sachin

startsWith() and endsWith() method


class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true

}
}
Output:true
true

charAt() method
class Simple{
public static void main(String args[]){

String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h

}
}
Output:S
h

length() method
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.length());//6
}
}
Output:6

intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the pool
is returned. Otherwise, this String object is added to the pool and a reference to this
String object is returned.
class Simple{
public static void main(String args[]){
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
}

}
Output:Sachin

StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.

Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it


simultaneously .So it is safe and will result in an order.

Commonly used Constructors of StringBuffer class:


1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.

Commonly used methods of StringBuffer class:


1. public synchronized StringBuffer append(String s): is used to append the
specified string with this string. The append() method is overloaded like
append(char), append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to
insert the specified string with this string at the specified position. The insert()
method is overloaded like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex,
String str): is used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is
used to delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex): is used to return the substring from

the specified beginIndex.


11. public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.

What is mutable string?


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

simple example of StringBuffer class by append() method


The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

Example of replace() method of StringBuffer class


The replace() method replaces the given string from the specified beginIndex and
endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");

sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

Example of reverse() method of StringBuffer class


The reverse() method of StringBuilder class reverses the current string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Example of capacity() method of StringBuffer class


The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");


System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Example of ensureCapacity() method of StringBuffer class


The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases
the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK1.5.

Commonly used Constructors of StringBuilder class:


1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified

capacity as length.

Commonly used methods of StringBuilder class:


1. public StringBuilder append(String s): is used to append the specified string
with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public StringBuilder insert(int offset, String s): is used to insert the specified
string with this string at the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public StringBuilder replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public StringBuilder delete(int startIndex, int endIndex): is used to delete
the string from specified startIndex and endIndex.
5. public StringBuilder reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex): is used to return the substring from
the specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.

simple program of StringBuilder class by append() method


The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");

sb.append("Java");//now original string is changed


System.out.println(sb);//prints Hello Java
}
}

Example of insert() method of StringBuilder class


The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

Example of replace() method of StringBuilder class


The replace() method replaces the given string from the specified beginIndex and
endIndex.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

Example of delete() method of StringBuilder class


The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

Example of reverse() method of StringBuilder class


The reverse() method of StringBuilder class reverses the current string.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Example of capacity() method of StringBuilder class


The capacity() method of StringBuilder class returns the current capacity of the Builder.
The default capacity of the Builder is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Example of ensureCapacity() method of StringBuilder class


The ensureCapacity() method of StringBuilder class ensures that the given capacity is
the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16

sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

How to create Immutable class?


There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable. We can also
create immutable class by creating final class that have final data members as the
example given below:

Example to create Immutable class


In this example, we have created a final class named Employee. It have one final
datamember, a parameterized constructor and getter method.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}

The above class is immutable because:

The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.

The class is final so we cannot create the subclass.

There is no setter methods i.e. we have no option to change the value of the

instance variable.
These points makes this class as immutable.

Understanding toString() method


If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an
object etc. depends on your implementation.

Advantage of the toString() method


By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.

Understanding problem without toString() method


Let's see the simple code that prints reference.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of
the objects but I want to print the values of these objects. Since java compiler internally

calls toString() method, overriding this method will return the specified values. Let's
understand it with the example given below:

Example of toString() method


Now let's see the real example of toString() method.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:101 Raj lucknow
102 Vijay ghaziabad

StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class


There are 3 constructors defined in the StringTokenizer class.
Constructor

Description

StringTokenizer(String str)

creates StringTokenizer with specified string.

StringTokenizer(String str, String


delim)

creates StringTokenizer with specified string and delimeter.

StringTokenizer(String str, String


delim, boolean returnValue)

creates StringTokenizer with specified string, delimeter and


returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters serve
to separate tokens.

Methods of StringTokenizer class


The 6 useful methods of StringTokenizer class are as follows:
Public method

Description

boolean hasMoreTokens()

checks if there is more tokens available.

String nextToken()

returns the next token from the StringTokenizer object.

String nextToken(String delim)

returns the next token based on the delimeter.

boolean hasMoreElements()

same as hasMoreTokens() method.

Object nextElement()

same as nextToken() but its return type is Object.

int countTokens()

returns the total number of tokens.

Simple example of StringTokenizer class


Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan

Example of nextToken(String delim) method of


StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
my,name,is,khan");

StringTokenizer st = new StringTokenizer("

// printing next token


System.out.println("Next token is : " + st.nextToken(","));

}
}
Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split() method of String


class or regex (Regular Expression).

Exception Handling in Java


1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
1.

Checked Exception

2.

Unchecked Exception

3.

Error

5. Scenarios where exception may occur


The exception handling is one of the powerful mechanism provided in java. It provides the
mechanism to handle the runtime errors so that normal flow of the application can be
maintained.
In this page, we will know about exception, its type and the difference between checked and
unchecked exceptions.

Exception

Dictionary Meaning:Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Exception Handling
Exception Handling is a mechanism to handle runtime errors.

Advantage of Exception Handling


The core advantage of exception handling is that normal flow of the application is
maintained. Exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If
we perform exception handling, rest of the exception will be executed. That is why we
use exception handling.

Do You Know ?

What is the difference between checked and unchecked exceptions ?

What happens behind the code int data=50/0; ?

Why use multiple catch block ?

Is there any possibility when finally block is not executed ?

What is exception propagation ?

What is the difference between throw and throws keyword ?

What are the 4 rules for using exception handling with method overriding ?

Hierarchy of Exception classes

Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

What is the difference between checked and unchecked


exceptions ?
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.

3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may


occur
There are given some scenarios where unchecked exceptions can occur. They are as
follows:

1) Scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have
a string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Use of try-catch block in Exception handling:


Five keywords used in Exception handling:
1. try
2. catch
3. finally
4. throw
5. throws

try block
Enclose the code that might throw an exception in try block. It must be used within the
method and must be followed by either catch or finally block.

Syntax of try with catch block


try{
...
}catch(Exception_class_Name reference){}

Syntax of try with finally block


try{
...
}finally{}

catch block
Catch block is used to handle the Exception. It must be used after the try block.

Problem without exception handling


class Simple{
public static void main(String args[]){
int data=50/0;
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed i.e. rest of the
code... statement is not printed. Let's see what happens behind the scene:

What happens behind the code int a=50/0;

The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:

Prints out exception description.

Prints the stack trace (Hierarchy of methods where the exception occurred).

Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application
is maintained i.e. rest of the code is executed.

Solution by exception handling


class Simple{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the
code... statement is printed.

Multiple catch block:


If you have to perform different tasks at the occrence of different Exceptions, use
multple catch block.
<b><i>Example of multiple catch block</i></b>
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:task1 completed
rest of the code...

Rule:At a time only one Exception is occured and at a time only one catch block is
executed.
Rule:All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;

}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:Compile-time error

Nested try block:


try block within a try block is known as nested try block.

Why use nested try block?


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Example:
<b><i>Example of nested try block</i></b>
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;

}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}

finally block
The finally block is a block that is always executed. It is mainly used to perform some
important tasks such as closing connection, stream etc.

Note:Before terminating the program, JVM executes finally block(if any).


Note:finally must be followed by try or catch block.

Why use finally block?

finally block can be used to put "cleanup" code such as closing a file,closing
connection etc.

case 1
Program in case exception does not occur

class Simple{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

case 2
Program in case exception occured but not handled
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

case 3
Program in case exception occured and handled
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");

}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit()
or by causing a fatal error that causes the process to abort).

throw keyword
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used
to throw custom exception. We will see custom exceptions later.

Example of throw keyword


In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
class Excep13{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}

}
Output:Exception in thread main java.lang.ArithmeticException:not valid

Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method,If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they reach
the very bottom of the call stack.This is called exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Program of Exception Propagation


class Simple{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Simple obj=new Simple();
obj.p();
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...

In the above example exception occurs in m() method where it is not handled,so it is
propagated to previous n() method where it is not handled, again it is propagated to p()
method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p()
method,n() method or m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Program which describes that checked exceptions are not propagated


class Simple{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
Simple obj=new Simple();
obj.p();
System.out.println("normal flow");
}
}
Output:Compile Time Error

throws keyword
The throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Syntax of throws keyword:


void method_name() throws exception_class_name{
...
}

Que) Which exception should we declare?


Ans) checked exception only, because:

unchecked Exception: under your control so correct your code.

error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of throws keyword:


Now Checked Exception can be propagated (forwarded in call stack).

Program which describes that checked exceptions can be propagated by throws


keyword.
import java.io.IOException;
class Simple{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Simple obj=new Simple();
obj.p();
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you


must either caught or declare the exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.

import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");

}
}
class Test{
public static void main(String args[]){
try{
Test t=new Test();
t.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}

}
Output:exception handled
normal flow...

Case2: You declare the exception

A)In case you declare the exception, if exception does not occur, the code will be
executed fine.

B)In case you declare the exception if exception occures, an exception will be thrown
at runtime because throws does not handle the exception.

A)Program if exception does not occur


import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Test{
public static void main(String args[])throws IOException{//declare exception
Test t=new Test();
t.method();
}

System.out.println("normal flow...");

}
Output:device operation performed
normal flow...
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{

throw new IOException("device error");


}
}
class Test{
public static void main(String args[])throws IOException{//declare exception
Test t=new Test();
t.method();
}

System.out.println("normal flow...");

}
Output:Runtime Exception

Difference between throw and throws:


throw keyword

throws keyword

1)throw is used to explicitly throw an exception.

throws is used to declare an exception.

2)checked exception can not be propagated


without throws.

checked exception can be propagated with


throws.

3)throw is followed by an instance.

throws is followed by class.

4)throw is used within the method.

throws is used with the method signature.

5)You cannot throw multiple exception

You can declare multiple exception e.g.


public void method()throws
IOException,SQLException.

Que) Can we rethrow an exception?


Yes by throwing same exception in catch block.

ExceptionHandling with MethodOverriding


There are many rules if we talk about methodoverriding with exception handling. The
Rules are as follows:

If the superclass method does not declare an exception

If the superclass method does not declare an exception, subclass


overridden method cannot declare the checked exception but it can
declare unchecked exception.

If the superclass method declares an exception


o

If the superclass method declares an exception, subclass overridden


method can declare same, subclass exception or no exception but cannot
declare parent exception.

If the superclass method does not declare an exception


1) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class Child extends Parent{
void msg()throws IOException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
}
}
Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");} }
class Child extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
}

}
Output:child

If the superclass method declares an exception


1) Rule: If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent


exception
import java.io.*;
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}

}
Output:Compile Time Error

Example in case subclass overridden method declares same


exception
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws Exception{System.out.println("child");}

public static void main(String args[]){


Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}

Output:child

Example in case subclass overridden method declares subclass


exception
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}

}
Output:child

Example in case subclass overridden method declares no


exception
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg(){System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}

}
Output:child

Custom Exception
If you are creating your own Exception that is known as custom exception or user-

defined exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class Excep13{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
}

System.out.println("rest of the code...");

}
Output:Exception occured: InvalidAgeException:not valid
rest of the code...

Nested classes in Java


1. Nested classes
2. Advantage of Nested classes
3. Difference between nested class and inner class
4. Types of Nested classes
A class declared inside a class is known as nested class.
We use nested classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable code.
Additionally, it can access all the members of outer class including private data members
and methods.

Syntax of Nested class


class Outer_class_Name{
...

class Nested_class_Name{
...
}
...
}

Advantage of nested classes


There are basically three advantages of nested classes. They are

Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.

Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

Code Optimization: It requires less code to write.

Do You Know ?

What is the internal code generated by the compiler for member inner class ?

What are the two ways to create annonymous inner class ?

Can we access the non-final local variable inside the local inner class ?

How to access the static nested class ?

Can we define an interface within the class ?

Can we define a class within the interface ?

Q) Difference between nested class and inner class in Java?


Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested class:


There are two types of nested classes non-static and static nested classes.The non-static
nested classes are also known as inner classes.
1. non-static nested class(inner class)
o

a)Member inner class

b)Annomynous inner class

c)Local inner class

2. static nested class

1)Member inner class


A class that is declared inside a class but outside a method is known as member inner
class.

Invocation of Member Inner class


1. From within the class
2. From outside the class

Example of member inner class that is invoked inside a


class
In this example, we are invoking the method of member inner class from the display
method of Outer class.
class Outer{
private int data=30;
class Inner{

void msg(){System.out.println("data is "+data);}


}
void display(){
Inner in=new Inner();
in.msg();
}
public static void main(String args[]){
Outer obj=new Outer();
obj.display();
}
}
Output:data is 30

Internal code generated by the compiler for member inner class:


The java compiler creates a class file named Outer$Inner in this case. The Member inner
class have the reference of Outer class that is why it can access all the data members of
Outer class including private.
import java.io.PrintStream;
class Outer$Inner
{
final Outer this$0;
Outer$Inner()
{ super();
this$0 = Outer.this;
}
void msg()
{
System.out.println((new StringBuilder()).append("data is ")
.append(Outer.access$000(Outer.this)).toString());
}
}

Example of member inner class that is invoked outside


a class
In this example, we are invoking the msg() method of Inner class from outside the outer
class i.e. Test class.
<b><i>//Program of member inner class that is invoked outside a class</i></b>
class Outer{
private int data=30;
class Inner{
void msg(){System.out.println("data is"+data);}
}
}
class Test{
public static void main(String args[]){
Outer obj=new Outer();
Outer.Inner in=obj.new Inner();
in.msg();
}
}
Output:data is 30

2)Annonymous inner class


A class that have no name is known as annomymous inner class.
Annonymous class can be created by:
1. Class (may be abstract class also).
2. Interface
3.

Program of annonymous inner class by abstract class

abstract class Person{


abstract void eat();
}
class Emp{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Output:nice fruits

What happens behind this code?


Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
}
}
1. A class is created but its name is decided by the compiler which extends the Person
class and provides the implementation of the eat() method.
2. An object of Annonymous class is created that is reffered by p reference variable of
Person type. As you know well that Parent class reference variable can refer the
object of Child class.

The internal code generated by the compiler for anonymous


inner class
import java.io.PrintStream;
static class Emp$1 extends Person

Emp$1(){}
void eat()
{
System.out.println("nice fruits");
}

Program of annonymous inner class by interface


interface Eatable{
void eat();
}
class Emp{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Output:nice fruits

What does the compiler for annonymous inner class created by


interface
It performs two main tasks behind this code:
Eatable p=new Eatable(){
void eat(){System.out.println("nice fruits");}
};
}
}
1. A class is created but its name is decided by the compiler which implements the
Eatable interface and provides the implementation of the eat() method.
2. An object of Annonymous class is created that is reffered by p reference variable of
Eatable type. As you know well that Parent class reference variable can refer the
object of Child class.

The internal code generated by the compiler for annonymous


inner class created by interface
import java.io.PrintStream;
static class Emp$1 implements Eatable

{
Emp$1(){}
void eat(){System.out.println("nice fruits");}
}

3)Local inner class


A class that is created inside a method is known as local inner class. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.

Program of local inner class


class Simple{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
Simple obj=new Simple();
obj.display();
}
}
Output:30

Internal code generated by the compiler for local inner class


In such case, compiler creates a class named Simple$1Local that have the reference of
the outer class.
import java.io.PrintStream;
class Simple$1Local
{
final Simple this$0;
Simple$1Local()
{
super();
this$0 = Simple.this;
}
void msg()
{
System.out.println(Simple.access$000(Simple.this));
}

Rule: Local variable can't be private, public or protected.

Rules for Local Inner class

1) Local inner class cannot be invoked from outside the method.


2) Local inner class cannot access non-final local variable.

Program of accessing non-final local variable in local inner class


class Simple{
private int data=30;//instance variable
void display(){
int value=50;//local variable must be final
class Local{
void msg(){System.out.println(value);}//C.T.Error
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
Simple obj=new Simple();
obj.display();
}
}
Output:Compile Time Error

Program of accessing final local variable in local inner class


class Simple{
private int data=30;//instance variable
void display(){
final int value=50;//local variable must be final
class Local{
void msg(){System.out.println(data+" "+value);}//ok
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
Simple obj=new Simple();
obj.display();
}
}
Output:30 50

4)static nested class


A static class that is created inside a class is known as static nested class. It cannot access
the non-static members.

It can access static data members of outer class including private.

static nested class cannot access non-static (instance) data member or method.

Program of static nested class that have instance method


class Outer{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
Outer.Inner obj=new Outer.Inner();
obj.msg();
}

}
Output:data is 30

In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.

Internal code generated by the compiler for static nested class


import java.io.PrintStream;
static class Outer$Inner
{
Outer$Inner(){}
void msg(){
System.out.println((new StringBuilder()).append("data is ")
.append(Outer.data).toString());
}
}

Program of static nested class that have static method


class Outer{
static int data=30;

static class Inner{


static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
Outer.Inner.msg();//no need to create the instance of static nested class
}

}
Output:data is 30

Nested Interface
An interface which is declared within another interface or class is known as nested
interface. The nested interfaces are used to group related interfaces so that they can be
easy to maintain. The nested interface must be referred by the outer interface or class.
It can't be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java programmer.

Nested interface must be public if it is declared inside the interface but it can
have any access modifier if declared within the class.

Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface


interface interface_name{
...
interface nested_interface_name{
...
}
}

Syntax of nested interface which is declared within the class


class class_name{
...
interface nested_interface_name{
...
}
}

Example of nested interface which is declared within the interface


In this example, we are going to learn how to declare the nested interface and how we
can access it.
interface Showable{
void show();
interface Message{
void msg();
}
}
class Test implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}
public static void main(String args[]){
Showable.Message message=new Test();//upcasting here
message.msg();
}
}

Output:hello nested interface


As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside
the room, we cannot access the almirah directly because we must enter the room first.
In collection frameword, sun microsystem has provided a nested interface Entry. Entry is
the subinterface of Map i.e. accessed by Map.Entry.

Internal code generated by the java compiler for nested interface


Message
The java compiler internally creates public and static interface as displayed below:.
public static interface Showable$Message
{
public abstract void msg();
}

Example of nested interface which is declared within the class


Let's see how can we define an interface inside the class and how can we access it.
class A{
interface Message{
void msg();
}

}
class Test implements A.Message{
public void msg(){System.out.println("Hello nested interface");}
public static void main(String args[]){
A.Message message=new Test();//upcasting here
message.msg();
}
}

Output:hello nested interface

Can we define a class inside the interface ?


Yes, Ofcourse! If we define a class inside the interface, java compiler creates a static
nested class. Let's see how can we define a class within the interface:
interface M{
class A{}
}

Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading is a process of executing multiple threads simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than mulitprocessing because threads share a common memory area.
They don't allocate separate memory area so save memory, and context-switching
between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking

to utilize the CPU. Multitasking can be achieved by two ways:

Process-based Multitasking(Multiprocessing)

Thread-based Multitasking(Multithreading)

1)Process-based Multitasking (Multiprocessing)

Each process have its own address in memory i.e. each process allocates separate
memory area.

Process is heavyweight.

Cost of communication between the process is high.

Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.

2)Thread-based Multitasking (Multithreading)

Threads share the same address space.

Thread is lightweight.

Cost of communication between the thread is low.

Note:At least one process is required for each thread.

What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path
of execution. It shares the memory area of process.

As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
Note:At a time only one thread is executed.

Do You Know ?

Why your class, which extends the Thread class, object is treated as thread ?
Who is responsible for it ?

How to perform two tasks by two threads ?

How to perform multithreading by annonymous class ?

What is the Thread Schedular and what is the difference between preemptive
scheduling and time slicing ?

What happens if we start a thread twice ?

What happens if we call the run() method instead of start() method ?

What is the purpose of join method ?

Why JVM terminates the daemon thread if there is no user threads remaining ?

What is the shutdown hook?

What is garbage collection ?

What is the purpose of finalize() method ?

What does gc() method ?

What is synchronization and why use synchronization ?

What is the difference between synchronized method and synchronized block ?

What are the two ways to perform static synchronization ?

What is deadlock and when it can occur ?

What is interthread-communication or cooperation ?

What we will learn in Multithreading ?

Multithreading

Life Cycle of a Thread

Two ways to create a Thread

How to perform multiple tasks by multiple threads

Thread Schedular

Sleeping a thread

Can we start a thread twice ?

What happens if we call the run() method instead of start() method ?

Joining a thread

Naming a thread

Priority of a thread

Daemon Thread

ShutdownHook

Garbage collection

Synchronization with synchronized method

Synchronized block

Static synchronization

Deadlock

Inter-thread communication

Life cycle of a Thread (Thread States)


A thread can be in one of the five states in the thread. According to sun, there is only 4
states new, runnable, non-runnable and terminated. There is no running state. But for
better understanding the threads, we are explaining it in the 5 states. The life cycle of
the thread is controlled by JVM. The thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1)New
The thread is in new state if you create an instance of Thread class but before the

invocation of start() method.

2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3)Running
The thread is in running state if the thread scheduler has selected it.

4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

5)Terminated
A thread is in terminated or dead state when its run() method exits.

How to create thread:


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.

21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:

A new thread starts(with new callstack).

The thread moves from New state to the Runnable state.

When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...

Who makes your class object as thread object?


Thread class constructor allocates a new thread object.When you create object of
Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread
class constructor is invoked(by super() as first statement).So your Multi class object is

thread object now.

2)By implementing the Runnable interface:


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.

The Thread Schedular:

The thread scheduler is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread
schedular.

Only one thread at a time can run in a single process.

The thread schedular mainly uses preemptive or time slicing scheduling to schedule
the threads.

What is the difference between preemptive scheduling and time


slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.

Sleeping a thread (sleep() method):


The sleep() method of Thread class is used to sleep a thread for the specified

time.Syntax:

Syntax of sleep() method:


The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds)throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws InterruptedException

//<b><i>Program of sleep() method</i></b>


class Multi extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
t1.start();
t2.start();
}

Output:1
1
2
2
3
3
4
4
5
5
As you know well that at a time only one thread is executed. If you sleep a thread for
the specified time,the thread shedular picks up another thread and so on.

Can we start a thread twice?


No. After staring a thread, it can never be started again. If you does so, an

IllegalThreadStateException is thrown. For Example:


class Multi extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
t1.start();
}
}
Output:running
Exception in thread "main" java.lang.IllegalThreadStateException

What if we call run() method directly instead start()


method?

Each thread starts in a separate call stack.

Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.

class Multi extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.run();//fine, but does not start a separate call stack
}
}
Output:running...

//<b><i>Problem if you direct call run() method</i></b>


class Multi extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
t1.run();
t2.run();
}
}
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1
and t2 will be treated as normal object not thread object.

The join() method:


The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
//<b><i>Example of join() method</i></b>
class Multi extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);

}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
Multi t3=new Multi();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.
//<b><i>Example of join(long miliseconds) method</i></b>
class Multi extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){

Multi t1=new Multi();


Multi t2=new Multi();
Multi t3=new Multi();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5

In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then
t2 and t3 starts executing.

getName(),setName(String) and getId() method:


public String getName()
public void setName(String name)
public long getId()
class Multi6 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
Multi6 t1=new Multi6();
Multi6 t2=new Multi6();

System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...

The currentThread() method:


The currentThread() method returns a reference to the currently executing thread
object.

Syntax:
public static Thread currentThread()
//<b><i>Example of currentThread() method</i></b>
class Multi6 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi6 t1=new Multi6();
Multi6 t2=new Multi6();
t1.start();
t2.start();
}
}
Output:Thread-0
Thread-1

Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.

Example of naming a thread:


class Multi6 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
Multi6 t1=new Multi6();
Multi6 t2=new Multi6();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...

The currentThread() method:


The currentThread() method returns a reference to the currently executing thread
object.

Syntax of currentThread() method:

public static Thread currentThread(): returns the reference of currently running

thread.

Example of currentThread() method:

class Multi6 extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi6 t1=new Multi6();
Multi6 t2=new Multi6();
t1.start();
t2.start();
}
}
Output:Thread-0
Thread-1

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.

3 constants defiend in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class Multi10 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
Multi10 m1=new Multi10();
Multi10 m2=new Multi10();
m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running
running
running
running

thread
thread
thread
thread

name is:Thread-0
priority is:10
name is:Thread-1
priority is:1

Daemon Thread
There are two types of threads user thread and daemon thread. The daemon thread is a
service provider thread. It provides services to the user thread. Its life depends on the
user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.

Points to remember for Daemon Thread:

It provides services to user threads for background supporting tasks. It has no role
in life than to serve user threads.

Its life depends on user threads.

It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread


remaining?
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running
this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Daemon thread:


The java.lang.Thread class provides two methods related to daemon thread

public void setDaemon(boolean status): is used to mark the current thread


as daemon thread or user thread.

public boolean isDaemon(): is used to check that current is daemon.

Simple example of Daemon thread


class MyThread extends Thread{

public void run(){


System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String[] args){
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setDaemon(true);
t1.start();
t2.start();
}
}
Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false

Note: If you want to make a user thread as Daemon, it must not be started otherwise
it will throw IllegalThreadStateException.
class MyThread extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String[] args){
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t1.setDaemon(true);//will throw exception here
t2.start();
}
}
Output:exception in thread main: java.lang.IllegalThreadStateException

Thread Pooling in Java


Thread pool represents a group of worker threads that are waiting for the job. Here, threads
are executed whenever they get the job.
In case of thread pool, a group of fixed size threads are created. A thread from the thread
pool is pulled out and assigned a job by the service provider. After completion of the job,
thread is contained in the thread pool again.

Advantage of Thread Pool


Better performance It saves time because there is no need to create new thread.

Where is it used?
It is used in Servlet and JSP where container creates a thread pool to process the request.

Example of Java Thread Pool


Let's see a simple example of java thread pool using executors and ThreadPoolExecutor.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message =
"+message);
processmessage();
System.out.println(Thread.currentThread().getName()+" (End)");
}
private void processmessage() {
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace();
}
}
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) { }
}

System.out.println("Finished all threads");

Output:

pool-1-thread-1 (Start) message = 0


pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads

How to perform single task by multiple threads?


If you have to perform single task by many threads, have only one run() method.For
example:
//<b><i>Program of performing single task by multiple threads</i></b>
class Multi extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
Multi t3=new Multi();
t1.start();
t2.start();
t3.start();
}

}
Output:task one
task one
task one
//<b><i>Program of performing single task by multiple threads</i></b>
class Multi3 implements Runnable{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Thread t1 =new Thread(new Multi3());//passing annonymous object of Multi3 class
Thread t2 =new Thread(new Multi3());
t1.start();
t2.start();
}
}
Output:task one
task one

Note: Each thread run in a separate callstack.

How to perform multiple tasks by multiple threads (multitasking in


multithreading)?
If you have to perform multiple tasks by multiple threads,have multiple run()
methods.For example:
//<b><i>Program of performing two tasks by two threads</i></b>
class Simple1 extends Thread{
public void run(){
System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){
System.out.println("task two");
}
}
class Test{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Output:task one
task two

Same example as above by annonymous class that extends


Thread class:
//<b><i>Program of performing two tasks by two threads</i></b>
class Test{
public static void main(String args[]){
Thread t1=new Thread(){
public void run(){
System.out.println("task one");
}
};
Thread t2=new Thread(){
public void run(){
System.out.println("task two");
}
};

t1.start();
t2.start();
}
}
Output:task one
task two

Same example as above by annonymous class that implements


Runnable interface:
//<b><i>Program of performing two tasks by two threads</i></b>
class Test{
public static void main(String args[]){
Runnable r1=new Runnable(){
public void run(){
System.out.println("task one");
}
};
Runnable r2=new Runnable(){
public void run(){
System.out.println("task two");
}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
t1.start();
t2.start();
}
}
Output:task one
task two

Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.

Advantage of Garbage Collection:

It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.

It is automatically done by the garbage collector so we don't need to make extra


efforts.

How can an object be unreferenced?


There are many ways:

By nulling the reference

By assigning a reference to another

By annonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:
1.

new Employee();

finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in System
class as:
1.

protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created
by new keyword. So if you have created any object without new, you can use
finalize method to perform cleanup processing (destroying remaining objects).

gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
1.

public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage


Collector(GC). This thread calls the finalize() method before object is garbage
collected.

Simple Example of garbage collection:


class Simple{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
Simple s1=new Simple();
Simple s2=new Simple();
s1=null;
s2=null;
System.gc();
}
}
Output:object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Synchronization
Synchronization is the capability of control the access of multiple threads to any shared
resource. Synchronization is better in case we want only one thread can access the shared
resource at a time.

Why use Synchronization?


The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

Mutual Exclusive

1. Synchronized method.
2. Synchronized block.
3. static synchronization.

Cooperation (Inter-thread communication)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization

Understanding the concept of Lock


Synchronization is built around an internal entity known as the lock or monitor.Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock
implementations.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:
Class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Use{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
100
10
200

15
300
20
400
25
500

Solution by synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the method returns.

//Program of synchronized method


Class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

class Use{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

Same Example of synchronized method by using annonymous


class
In this program, we have created the two threads by annonymous class, so less coding is
required.
//Program of synchronized method by using annonymous class
Class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class Use{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);

}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block

Synchronized block is used to lock an object for any shared resource.

Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}

Example of synchronized block


Let's see the simple example of synchronized block.

<b><i>//Program of synchronized block</i></b>


class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Use{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:5
10
15
20
25
100

200
300
400
500

Same Example of synchronized block by using


annonymous class:
<b><i>//Program of synchronized block by using annonymous class</i></b>
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class Use{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
Output:5
10
15
20
25

100
200
300
400
500

Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization


Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In
case of synchronized method and synchronized block there cannot be interference between
t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single
lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires
another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2
and t4.Static synchronization solves this problem.

Example of static synchronization


In this example we are applying synchronized keyword on the static method to perform
static synchronization.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);

try{
Thread.sleep(400);
}catch(Exception e){}

}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}

class MyThread4 extends Thread{


public void run(){
Table.printTable(1000);
}
}
class Use{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output: 1
2
3
4
5
6

7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Same example of static synchronization by annonymous


class
In this example, we are using annonymous class to create the threads.
class Table{
synchronized static void printTable(int n){

for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1=new Thread(){
public void run(){
Table.printTable(1);
}
};
Thread t2=new Thread(){
public void run(){
Table.printTable(10);
}
};
Thread t3=new Thread(){
public void run(){
Table.printTable(100);
}
};
Thread t4=new Thread(){
public void run(){
Table.printTable(1000);
}
};
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output: 1
2
3
4
5
6
7
8
9

10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Synchronized block on a class lock:


The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:
static void printTable(int n) {
synchronized (Table.class) {
// ...
}
}

// Synchronized block on class A

Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the
lock, the condition is called deadlock.

Example of Deadlock in java:


public class DeadlockExample {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}

}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};

t1.start();
t2.start();
}

Output: Thread 1: locked resource 1


Thread 2: locked resource 2

Inter-thread communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads
to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

wait()

notify()

notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method

Description

public final void wait()throws InterruptedException

waits until object is notified.

public final void wait(long timeout)throws


InterruptedException

waits for the specified amount of


time.

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:
public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.

6. After completion of the task, thread releases the lock and exits the monitor state of
the object.

Why wait(), notify() and notifyAll() methods are defined in Object


class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.
wait()

sleep()

wait() method releases the lock

sleep() method doesn't release the lock.

is the method of Object class

is the method of Thread class

is the non-static method

is the static method

is the non-static method

is the static method

should be notified by notify() or notifyAll()


methods

after the specified amount of time, sleep is


completed.

Example of inter thread communication in java


Let's see the simple example of inter thread communication.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;

System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets
the interrupt flag to true. Let's first see the methods provided by the Thread class for
thread interruption.

The 3 methods provided by the Thread class for interrupting a thread

public void interrupt()

public static boolean interrupted()

public boolean isInterrupted()

Example of interrupting a thread that stops working

In this example, after interrupting the thread, we are propagating it, so it will stop
working. If we don't want to stop the thread, we can handle it where sleep() or wait()
method is invoked. Let's first see the example where we are propagating the exception.
class A extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
A t1=new A();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}

Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)

Example of interrupting a thread that doesn't stop working


In this example, after interrupting the thread, we handle the exception, so it will break
out the sleeping but will not stop working.
class A extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
public static void main(String args[]){

A t1=new A();
t1.start();
t1.interrupt();
}
}

Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...

Example of interrupting thread that behaves normally


If thread is not in sleeping or waiting state, calling the interrupt() method sets the
interrupted flag to true that can be used to stop the thread by the java programmer
later.
class A extends Thread{
public void run(){
for(int i=1;i<=5;i++)
System.out.println(i);
}
public static void main(String args[]){
A t1=new A();
t1.start();
t1.interrupt();
}
}
Output:1
2
3
4
5

What about isInterrupted and interrupted method?


The isInterrupted() method returns the interrupted flag either true or false. The static
interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is
true.

class InterruptedDemo extends Thread{


public void run(){
for(int i=1;i<=2;i++){
if(Thread.interrupted()){
System.out.println("code for interrupted thread");
}
else{
System.out.println("code for normal thread");
}
}//end of for loop
}
public static void main(String args[]){
InterruptedDemo t1=new InterruptedDemo();
InterruptedDemo t2=new InterruptedDemo();
t1.start();
t1.interrupt();
t2.start();
}
}
Output:Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread

Reentrant Monitor in Java


According to Sun Microsystems, Java monitors are reentrant means java thread can
reuse the same monitor for different synchronized methods if method is called from the
method.

Advantage of Reentrant Monitor


It eliminates the possibility of single thread deadlocking

Let's understand the java reentrant monitor by the example given below:

class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
In this class, m and n are the synchronized methods. The m() method internally calls the
n() method.
Now let's call the m() method on a thread. In the class given below, we are creating thread
using annonymous class.
class ReentrantExample{
public static void main(String args[]){
final Reentrant re=new Reentrant();
Thread t1=new Thread(){
public void run(){
re.m();//calling method of Reentrant class
}
};
t1.start();
}}
Output: this is n() method
this is m() method

Input and Output in Java


Input and Output (I/O) is used to process the input and produce the output based on the
input. Java uses the concept of stream to make I/O operations fast. java.io package
contains all the classes required for input and output operations.

Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a
stream because it's like a stream of water that continues to flow.
Three streams are created for us automatically:

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error

Do You Know ?

How to write a common data to multiple files using single stream only ?

How can we access multiple files by single stream ?

How can we improve the performance of Input and Output operation ?

How many ways can we read data from the keyboard?

What is console class ?

How to compress and uncompress the data of a file?

OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.

OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.

Commonly used methods of OutputStream class


Method

Description

1) public void write(int)throws


IOException:

is used to write a byte to the current output


stream.

2) public void write(byte[])throws


IOException:

is used to write an array of byte to the current


output stream.

3) public void flush()throws IOException:

flushes the current output stream.

4) public void close()throws IOException:

is used to close the current output stream.

InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an
input stream of bytes.

Commonly used methods of InputStream class


Method

Description

1) public abstract int read()throws


IOException:

reads the next byte of data from the input stream.It


returns -1 at the end of file.

2) public int available()throws


IOException:

returns an estimate of the number of bytes that can be


read from the current input stream.

3) public void close()throws


IOException:

is used to close the current input stream.

FileInputStream and FileOutputStream (File


Handling):
FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.

FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for characteroriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented
data.

Example of FileOutputStream class:


//<b><i>Simple program of writing data into the file</i></b>
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";

byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Output:success...

FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes
such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to read image etc.

Example of FileInputStream class:


//<b><i>Simple program of reading data from the file</i></b>
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fin.close();
}catch(Exception e){system.out.println(e);}
}

}
Output:Sachin is my favourite player.

Example of Reading the data of current java file and


writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file,
image file, video file etc. In this example, we are reading the data of C.java file and writing
it into another file M.java.
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}

ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data
is written to it.
Closing a ByteArrayOutputStream has no effect.

Commonly used Constructors of ByteArrayOutputStream class:


1) ByteArrayOutputStream():creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if necessary.
2) ByteArrayOutputStream(int size):creates a new byte array output stream, with a
buffer capacity of the specified size, in bytes.

Commonly used Methods of ByteArrayOutputStream class:


1) public synchronized void writeTo(OutputStream out) throws
IOException: writes the complete contents of this byte array output stream to the
specified output stream.

Example of ByteArrayOutputStream class:


//<b><i>Simple program of writing data by ByteArrayOutputStream class</i></b>
import java.io.*;
class S{
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(239);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
Output:success...

SequenceInputStream class:
SequenceInputStream class is used to read data from multiple streams.

Constructors of SequenceInputStream class:


1) SequenceInputStream(InputStream s1, InputStream s2):creates a new input
stream by reading the data of two input stream in order, first s1 and then s2.
2) SequenceInputStream(Enumeration e):creates a new input stream by reading
the data of an enumeration whose type is InputStream.

Simple example of SequenceInputStream class


In this example, we are printing the data of two files f1.txt and f2.txt.
//Program of SequenceInputStream that reads data of 2 files
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
int i;
while((i=sis.read())!=-1)
{

System.out.println((char)i);
}
}

Example of SequenceInputStream class that reads the


data from two files and write it into another
In this example, we are writing the data of two files f1.txt and f2.txt into another file
named f3.txt.
//reading data of 2 files and writing it into one file
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
FileOutputStream fout=new FileOutputStream("f3.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
int i;
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();
}

Example of SequenceInputStream class that reads the


data from multiple files using enumeration
If we need to read the data from more than two files, we need to have these information
in the Enumeration object. Enumeration object can be get by calling elements method of
the Vector class. Let's see the simple example where we are reading the data from the 4
files.
import java.io.*;
import java.util.*;
class B{
public static void main(String args[])throws IOException{

//creating the FileInputStream objects for all the files


FileInputStream fin=new FileInputStream("A.java");
FileInputStream fin2=new FileInputStream("abc2.txt");
FileInputStream fin3=new FileInputStream("abc.txt");
FileInputStream fin4=new FileInputStream("B.java");
//creating Vector object to all the stream
Vector v=new Vector();
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
//creating enumeration object by calling the elements method
Enumeration e=v.elements();
//passing the enumeration object in the constructor
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close();
}
}

BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data
directly into a stream. So, it makes the performance fast.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one
stream and send it into another. It is required if you have connected the one stream with
another.
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");

BufferedOutputStream bout=new BufferedOutputStream(fout);


String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
System.out.println("success");

}
}
Output:success...

Example of BufferedInputStream class:


//<b><i>Simple program of reading data from the file using buffer</i></b>
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1)
System.out.println((char)i);
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:Sachin is my favourite player

FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has
suggested not to use the FileInputStream and FileOutputStream classes if you have to read
and write the textual information.

Example of FileWriter class:


In this example, we are writing the data in the file abc.txt.
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.flush();

fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:success...

FileReader class:
FileReader class is used to read data from the file.

Example of FileReader class:


In this example, we are reading the data from the file abc.txt file.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:my name is sachin

CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements
the Appendable interface. Its buffer automatically grows when data is written in this stream.
Calling the close() method on this object has no effect.

Example of CharArrayWriter class:


In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("my name is");
FileWriter f1=new FileWriter("a.txt");
FileWriter f2=new FileWriter("b.txt");
FileWriter f3=new FileWriter("c.txt");

FileWriter f4=new FileWriter("d.txt");


out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
}
}

Reading data from keyboard:


There are many ways to read data from the keyboard. For example:

InputStreamReader

Console

Scanner

DataInputStream etc.

InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:

connects to input stream of keyboard

converts the byte-oriented stream into character-oriented stream

BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by


InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the
InputStreamReaderstream for reading the line by line data from the keyboard.
//<b><i>Program of reading data</i></b>
import java.io.*;
class G5{

public static void main(String args[])throws Exception{


InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Amit
Welcome Amit

Another Example of reading data from keyboard by


InputStreamReader and BufferdReader class until the
user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();

System.out.println("data is: "+name);


}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop

Console class (I/O)


The Console class can be used to get input from the keyboard.

How to get the object of Console class?


System class provides a static method named console() that returns the unique instance
of Console class.

Syntax:
1.

public static Console console(){}

Commonly used methods of Console class:


1) public String readLine(): is used to read a single line of text from the console.
2) public String readLine(String fmt,Object... args): it provides a formatted prompt
then reads the single line of text from the console.
3) public char[] readPassword(): is used to read password that is not being
displayed on the console.
4) public char[] readPassword(String fmt,Object... args): it provides a formatted
prompt then reads the password that is not being displayed on the console.

Example of Console class that reads name of user:


import java.io.*;
class A{
public static void main(String args[]){

Console c=System.console();
System.out.println("Enter your name");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}

Example of Console class that reads password:

import java.io.*;
class A{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password");
char[] ch=c.readPassword();
System.out.println("Password is");
for(char ch2:ch)
System.out.print(ch2);
}
}

java.util.Scanner class:
There are various ways to read input from the keyboard, the java.util.Scanner class is one
of them. The Scanner class breaks the input into tokens using a delimiter which is
whitespace bydefault. It provides many methods to read and parse various primitive values.

Commonly used methods of Scanner class:


There is a list of commonly used Scanner class methods:

public String next(): it returns the next token from the scanner.

public String nextLine(): it moves the scanner position to the next line and
returns the value as a string.

public byte nextByte(): it scans the next token as a byte.

public short nextShort(): it scans the next token as a short value.

public int nextInt(): it scans the next token as an int value.

public long nextLong(): it scans the next token as a long value.

public float nextFloat(): it scans the next token as a float value.

public double nextDouble(): it scans the next token as a double value.

Example of java.util.Scanner class:


Let's see the simple example of the Scanner class which reads the int, string and double
value as an input:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}

Output:Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream
class automatically flushes the data so there is no need to call flush() method. Moreover, its
methods don't throw IOException.

Commonly used methods of PrintStream class:


There are many methods in PrintStream class. Let's see commonly used methods of
PrintStream class:

public void print(boolean b): it prints the specified boolean value.

public void print(char c): it prints the specified char value.

public void print(char[] c): it prints the specified character array values.

public void print(int i): it prints the specified int value.

public void print(long l): it prints the specified long value.

public void print(float f): it prints the specified float value.

public void print(double d): it prints the specified double value.

public void print(String s): it prints the specified string value.

public void print(Object obj): it prints the specified object value.

public void println(boolean b): it prints the specified boolean value and
terminates the line.

public void println(char c): it prints the specified char value and terminates the
line.

public void println(char[] c): it prints the specified character array values and
terminates the line.

public void println(int i): it prints the specified int value and terminates the
line.

public void println(long l): it prints the specified long value and terminates the
line.

public void println(float f): it prints the specified float value and terminates the
line.

public void println(double d): it prints the specified double value and
terminates the line.

public void println(String s): it prints the specified string value and terminates
the line./li>

public void println(Object obj): it prints the specified object value and
terminates the line.

public void println(): it terminates the line only.

public void printf(Object format, Object... args): it writes the formatted


string to the current stream.

public void printf(Locale l, Object format, Object... args): it writes the

formatted string to the current stream.

public void format(Object format, Object... args): it writes the formatted


string to the current stream using specified format.

public void format(Locale l, Object format, Object... args): it writes the


formatted string to the current stream using specified format.

Example of java.io.PrintStream class:


In this example, we are simply printing integer and string values.
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("mfile.txt");
PrintStream pout=new PrintStream(fout);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}
}

Example of printf() method of java.io.PrintStream class:


Let's see the simple example of printing integer value by format specifier.
class PrintStreamTest{
public static void main(String args[]){
int a=10;
System.out.printf("%d",a);//Note, out is the object of PrintStream class
}
}
Output:10

Compressing and Uncompressing File


The DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress
and uncompress the data in the deflate compression format.

DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the data in the deflate compression
format. It provides facility to the other compression filters, such as GZIPOutputStream.

Example of Compressing file using DeflaterOutputStream class


In this example, we are reading data of a file and compressing it into another file using
DeflaterOutputStream class. You can compress any file, here we are compressing the
Deflater.java file
import java.io.*;
import java.util.zip.*;
class Compress{ public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("Deflater.java");
FileOutputStream fout=new FileOutputStream("def.txt");
DeflaterOutputStream out=new DeflaterOutputStream(fout);
int i;
while((i=fin.read())!=-1){
out.write((byte)i);
out.flush();
}
fin.close();
out.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
download this example

InflaterInputStream class:
The InflaterInputStream class is used to uncompress the file in the deflate compression
format. It provides facility to the other uncompression filters, such as GZIPInputStream
class.

Example of uncompressing file using InflaterInputStream classIn


this example, we are decompressing the compressed file def.txt into D.java .
import java.io.*;

import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}

PipedInputStream and PipedOutputStream classes


The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of
the PipedOutputStream class.

Example of PipedInputStream and PipedOutputStream classes


using threads
Here, we have created two threads t1 and t2. The t1 thread writes the data using the
PipedOutputStream object and the t2 thread reads the data from that pipe using the
PipedInputStream object. Both the piped stream object are connected with each other.
import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();
pout.connect(pin);//connecting the streams

//creating one thread t1 which writes the data


Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
try{
for(int i=65;i<=90;i++)
System.out.println(pin.read());
}catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}}

Serialization
Serialization is a mechanism of writing the state of an object into a byte stream. It is
mainly used in Hibernate, JPA, EJB etc. The reverse operation of the serialization is called
deserialization. The String class and all the wrapper classes implements Serializable
interface bydefault.

Advantage of Serialization
It is mainly used to travel object's state on the network.

About Serializable interface


Serializable is a marker interface(have no body). It is just used to "mark" Java classes
which support a certain capability. It must be implemented by the class whose object
you want to persist. Let's see the example given below:
import java.io.Serializable;

public class Student implements Serializable{


int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

ObjectOutputStream class:
An ObjectOutputStream is used to write primitive data types and Java objects to an
OutputStream.Only objects that support the java.io.Serializable interface can be written
to streams.

Commonly used Constructors:


1) public ObjectOutputStream(OutputStream out) throws IOException {}creates
an ObjectOutputStream that writes to the specified OutputStream.

Commonly used Methods:


1) public final void writeObject(Object obj) throws IOException {}write the
specified object to the ObjectOutputStream.
2) public void flush() throws IOException {}flushes the current output stream.

Example of Serialization
In this example, we are going to serialize the object of Student class. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object.
We are saving the state of the object in the file named f.txt.

import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Output:success

Deserilization:
Deserialization is the process of reconstructing the object from the serialized state.It is
the reverse operation of serialization.

ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

Commonly used Constructors:


1) public ObjectInputStream(InputStream in) throws IOException {}creates an
ObjectInputStream that reads from the specified InputStream.

Commonly used Methods:


1) public final Object readObject() throws IOException,
ClassNotFoundException{}reads an object from the input stream.

Example of Deserialization:
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}
Output:211 ravi

Serialization with Inheritance


If a class implements serializable then all its subclasses will also be serializable. Let's see
the example given below:
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee) {
super(id,name);
this.course=course;

this.fee=fee;
}
}
Now you can serialize the Student class object that extends the Person class which is
Serializable.Parent class properties are inherited to subclasses so if parent class is
Serializable, subclass would also be.

Externalizable interface:
The Externalizable interface provides the facility of writing the state of an object into a
byte stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:

public void writeExternal(ObjectOutput out) throws IOException

public void readExternal(ObjectInput in) throws IOException

Serialization with Static datamember


Note: If there is any static data member in a class, it will not be serialized becausestatic is
related to class not to instance.
class Employee implements Serializable{
int id;
String name;
static String companyName="IBM";//it won't be serialized
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Rule: In case of array or collection, all the objects of array or collection must be
serializable,if any object is not serialiizable then serialization will be failed.

The transient keyword


The transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized. Let's take an example, I have declared a class as
Student, it has three data members id, name and age. If you serialize the object, all the
values will be serialized but I don't want to serialize one value, e.g. age then we can
declare the age datamember as transient.

Example of transient keyword


In this example, we have created the two classes Student and Persist. One data member
of the Student class is declared as transient, it value will not be serialized. If
youdeserialize the object, it will return the default value for transient variable.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Output:success

Networking:
Networking is a concept of connecting two or more computing devices together so that
we can share resources.

Advantage:

sharing resources

centralize software management

Do You Know ?

How to perform connection-oriented Socket Programming in networking ?

How to display the data of any online web page ?

How to get the IP address of any host name e.g. www.google.com ?

How to perform connection-less socket programming in networking ?

What we will learn in Networking Tutorial ?

Networking and Networking Terminology

Socket Programming (Connection-oriented)

URL class

Displaying data of a webpage by URLConnection class

InetAddress class

DatagramSocket and DatagramPacket (Connection-less)

Networking Terminology:
There are some networking terminologies given below:

IP Address

Protocol

Port Number

MAC Address

Connection-oriented and connectionless protocol

Socket

IP Address:
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.

Protocol:
A protocol is a set of rules basically that is followed for communication. For example:

TCP

FTP

Telnet

SMTP

POP etc.

Socket Programming:
Socket programming is performed for communication between the machines. Socket
programming can be connection-oriented or connectionless. Socket and ServerSocket
classes are used for connection-oriented socket programming. The client in socket
programming must know two information:
1. IPaddress of Server, and
2. Port number.

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

Commonly used methods of Socket class:


1) public InputStream getInputStream()
2) public OutputStream getOutputStream()
3) public synchronized void close()

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

Commonly used methods of ServerSocket class:


1) public Socket accept()
1) public InputStream getInputStream()
2) public OutputStream getOutputStream()
3) public synchronized void close()

Example of Socket Programming:


//MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
//MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();

}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.

URL class:
The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:
1.

http://www.javatpoint.com/sonoojaiswal/index.jsp
A URL contains many informations:

Protocol: In this case, http is the protocol.

Server name or IP Address: In this case, www.javatpoint.com is the server


name.

Port Number: It is an optional attribute. If we write

http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number.

File Name or directory name: In this case, index.jsp is the file name.

Commonly used methods of URL class:

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.

Example of URL class:


//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/sonoojaiswal/index.jsp");
System.out.print("Protocol: "+url.getProtocol());
System.out.print("Host Name: "+url.getHost());
System.out.print("Port Number: "+url.getPort());
System.out.print("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /sonoojaiswal/index.jsp

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

How to get the object of URLConnection class:

The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
}

Displaying all the data 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. The getInputStream() method returns
all the data of the specified URL in the stream that can be read and displayed.

Example of Displaying all the data of a webpage by


URLConnecton class:
//DisplayData.java
import java.io.*;
import java.net.*;
public class DisplayData {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/sonoojaiswal/");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

InetAddress class:
The java.net.InetAddress class represents an IP address. The Inet Address class provides
methods to get the IP of any host name.

Commonly used methods of InetAddress class:

public static InetAddress getByName(String host) throws

UnknownHostException: it returns the IP of the given host.

public static InetAddress getLocalHost() throws


UnknownHostException: it returns the LocalHost IP and name.

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 InetAddress class:


//InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Output:Host Name: www.javatpoint.com
IP Address: 206.51.231.148

DatagramSocket and DatagramPacket (Networking)


DatagramSocket class
The DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. Datagram is basically an information but there is no guarantee of its
content, arrival or arrival time. The DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.

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.

DatagramPacket class:
The DatagramPacket is message that can be sent or received. If you send multiple
packet, it may arrive in any order. Moreover, 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.

Example of Sending DatagramPacket by DatagramSocket


/DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();

Example of Receiving DatagramPacket by DatagramSocket


//DReceiver.java
import java.net.*;
public class DReceiver{

public static void main(String[] args) throws Exception {


DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);

String str = new String(dp.getData(), 0, dp.getLength());


System.out.println(str);
ds.close();

Abstract Windowing Toolkit (AWT):


Abstract Windowing Toolkit (AWT) is used for GUI programming in java.

AWT Container Hierarchy:

Container:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container.

Window:
The window is the container that have no borders and menubars. You must use frame,
dialog or another window for creating a window.

Panel:
The Panel is the container that doesn't contain title bar and MenuBars. It can have other
components like button, textfield etc.

Frame:
The Frame is the container that contain title bar and can have MenuBars. It can have
other components like button, textfield etc.

Commonly used Methods of Component class:


1)public void add(Component c)
2)public void setSize(int width,int height)
3)public void setLayout(LayoutManager m)
4)public void setVisible(boolean)

Creating a Frame:
There are two ways to create a frame:

By extending Frame class (inheritance)

By creating the object of Frame class (association)

import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout now bydefault BorderLayout
setVisible(true);//now frame willbe visible, bydefault not visible
}
public static void main(String args[]){
First f=new First();
}
}

Simple example of AWT by association:


import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}

Event and Listener (Event Handling):


Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.

Event classes and Listener interfaces:


Event Classes

Listener Interfaces

ActionEvent

ActionListener

MouseEvent

MouseListener and MouseMotionListener

MouseWheelEvent

MouseWheelListener

KeyEvent

KeyListener

ItemEvent

ItemListener

TextEvent

TextListener

AdjustmentEvent

AdjustmentListener

WindowEvent

WindowListener

ComponentEvent

ComponentListener

ContainerEvent

ContainerListener

FocusEvent

FocusListener

Steps to perform EventHandling:


Following steps are required to perform event handling :
1. Implement the Listener interface and overrides its methods
2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration
methods. For example:

Button
o

MenuItem
o

public void addActionListener(ActionListener a){}

public void addTextListener(TextListener a){}

TextArea
public void addTextListener(TextListener a){}

Checkbox
o

public void addActionListener(ActionListener a){}

TextField

public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

Choice
o

public void addItemListener(ItemListener a){}

List
o

public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class

Example of event handling within class:


mport java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

Example of event handling by Outer class:


mport java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame implements ActionListener{
TextField tf;
AEvent2(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
dd(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent2(); }
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Example of event handling by Annonymous class:


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;

AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

Swing (Graphics Programming in java):


Swing is a part of JFC (Java Foundation Classes) that is used to create GUI application. It
is built on the top of AWT and entirely written in java.

Advantage of Swing over AWT:


There are many advantages of Swing over AWT. They are as follows:

Swing components are Plateform independent.

It is lightweight.

It supports pluggable look and feel.

It has more powerful components like tables, lists, scroll panes, color chooser,
tabbed pane etc.

It follows MVC (Model View Controller) architecture.

What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Swing (Graphics Programming in java):


Swing is a part of JFC (Java Foundation Classes) that is used to create GUI application.
It is built on the top of AWT and entirely written in java.

Advantage of Swing over AWT:


There are many advantages of Swing over AWT. They are as follows:

Swing components are Plateform independent.

It is lightweight.

It supports pluggable look and feel.

It has more powerful components like tables, lists, scroll panes, color chooser,
tabbed pane etc.

It follows MVC (Model View Controller) architecture.

What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Do You Know ?

How to display image on a button in swing?

How to change the component color by choosing a color from ColorChooser ?

How to display the digital watch in swing tutorial ?

How to create a notepad in swing?

How to create puzzle game and pic puzzle game in swing ?

How to create tic tac toe game in swing ?

Hierarchy of swing:

Commonly used Methods of Component class:


1)public void add(Component c)
2)public void setSize(int width,int height)
3)public void setLayout(LayoutManager m)
4)public void setVisible(boolean)

You might also like