0% found this document useful (0 votes)
8 views585 pages

Java Tutorial (Multithreadig)

Uploaded by

poojasubbu2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views585 pages

Java Tutorial (Multithreadig)

Uploaded by

poojasubbu2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 585

Java Tutorial

Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely used robust
technology. Let's start learning of java from basic questions like what is java tutorial, core java,
where it is used, what type of applications are created in java and why use java.
What is Java
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform:
Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.

Java Example
Let's have a quick look at java programming example. A detailed description of hello
java example is given in next page.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

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:
Desktop Applications such as acrobat reader, media player, antivirus etc.
Web Applications such as irctc.co.in, java.com etc.
Enterprise Applications such as banking applications.
● Mobile
● Embedded System
● Smart Card
● Robotics
● Games.

Types of Java Applications


There are mainly 4 type of applications that can be created using java programming:
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
Java history is interesting to know. The history of java starts from Green Team. 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.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions etc. There are given 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.

Why Oak name for java language?


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.
Why Java name for java language?
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. Current stable release of Java is Java SE 8.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java SE 8 (18th March, 2014)

Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
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:
Object
Class
Inheritance
Polymorphism
Abstraction
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 software-based 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:
Runtime Environment
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


In this page, we will learn how to write the simple program of java. We can write a
simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains main method. Let's
understand the requirement first.
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:
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
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.

To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:

As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open command prompt by start
menu -> All Programs -> Accessories -> command prompt.
To compile and run the above program, go to your current directory first; my current directory is
c:\new . Write here:

To compile: javac Simple.java


To execute: java Simple

How many ways can we 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.
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.
public static void main(String[] args)
public static void main(String []args)
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.
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");
}
};

Valid java main method signature


public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)

Invalid java main method signature


public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)

Resolving an error "javac is not recognized as an internal or external command"


?
If there occurs a problem like displayed in the below figure, you need to set path. Since DOS
doesn't know javac or java, we need to set path. Path is not required in such a case if you save
your program inside the jdk/bin folder. But its good approach to set path.

Internal Details of Hello Java Program


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, if the class is not public. It is explained in the figure given below:

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 in Java
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set
because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
temporary
permanent

1) How to set Temporary Path of JDK in Windows


To set the temporary path of JDK, you need to follow following steps:
Open command prompt
copy the path of jdk/bin directory
write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
2) How to set 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 Java 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 are having
brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtural Machine, move to the next page.
Firstly, let's see the basic differences between the JDK, JRE and JVM.
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. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following 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.

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

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).

What is JVM?
It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, and instance of JVM is created.
What it does?
The JVM performs following operation:
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 Register:


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

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Why char uses 2 byte in java and what is \u0000 ?


because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of
unicode system.To get detail about Unicode see below.

Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.

Why java uses Unicode System?


Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.

This caused two problems:


A particular code value corresponds to different letters in the various language standards.
The encodings for languages with large character sets have variable length.Some common
characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF

Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift operator,
bitwise operator, ternary operator and assignment operator.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

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 Procedure-oriented
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.

What is difference between object-oriented programming language and


object-based programming language?
Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.

Java Naming conventions


Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.

Advantage of naming conventions in java


By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important. It indicates that less time
is spent to figure out what the code does.
Name Convention
should start with uppercase letter and be a noun e.g. String, Color, Button,
class name
System, Thread etc.
interface should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name ActionListener etc.
should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
method name
print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants
should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
name

CamelCase in java naming conventions


Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.

Object and Class in Java


In this page, we will learn about java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it 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 behavior.

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 in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface

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 Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:0 null

Instance variable in Java


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
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 Student2{
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[]){


Student2 s1=new Student2();
Student2 s2=new Student2();

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

s1.displayInformation();
s2.displayInformation();

}
}

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
}
}
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.
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
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 objects

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

By changing number of arguments


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.
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.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){


Calculation2 obj=new Calculation2();
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:
class Calculation3{
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[]){


Calculation3 obj=new Calculation3();
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 Overloading1{
public static void main(int a){
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 OverloadingCalculation1{
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);}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
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 OverloadingCalculation2{
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[]){


OverloadingCalculation2 obj=new OverloadingCalculation2();
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 OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
public static void main(String args[]){
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}

Output:Compile Time Error


Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java 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 java constructor


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

Types of java constructors


There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


<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 Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:
Bike is created

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


default constructor.

Q) 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 Student3{
int id;
String name;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student3 s1=new Student3();
Student3 s2=new Student3();
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.

Java 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 Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


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

Output:
111 Karan
222 Aryan

Constructor Overloading in Java


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 Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(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[]){


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

Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
Method is used to expose behaviour
Constructor is used to initialize the state of an object.
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 Method is not provided by compiler in
don't have any constructor. any case.
Method name may or may not be
Constructor name must be same as the class name.
same as class name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy 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 in java. 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 java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Output:
111 Karan
111 Karan

Copying values 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 Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:
111 Karan
111 Karan

Q) 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.

Java static keyword


The static keyword in java is used for memory management mainly. We can apply java 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:
variable (also known as class variable)
method (also known as class method)
block
nested class

1) Java 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
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.

Java static property is shared to all objects.

Example of static variable


//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(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 Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}

Output:1
2
3

2) Java 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 Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

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


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (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:

The static method can not use non static data member or call non-static method directly.
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

Q) why java 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) Java 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 A2{
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

Q) 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 A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}

Output:static block is invoked (if not JDK7)


In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main
method as:
public static void main(String[] args)

this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.

1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;

Student10(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}

Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is
why we are using this keyword to distinguish between local variable and instance variable.

Solution of the above problem by this keyword


//example of this keyword
class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}

Output111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:

Program where this keyword is not required


class Student12{
int id;
String name;

Student12(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}

Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
//Program of this() constructor call (constructor chaining)

class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}

Student13(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}

Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan

Where to use this() constructor call?


The this() constructor call should be used to reuse the constructor in the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.
class Student14{
int id;
String name;
String city;

Student14(int id,String name){


this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){


Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}

Output:111 Karan null


222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.


class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}

Student15(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
}

Output:Compile Time Error


3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

Output:method is invoked

4) this keyword can be passed as an argument in the method.


The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}

public static void main(String args[]){


S2 s1 = new S2();
s1.p();
}
}

Output:method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to another
one.

5) The this keyword can be passed as argument in the constructor call.


We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10

6) The this keyword can be used to return current class instance.


We can return the this keyword as an statement from the method. In such case, return type of
the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


return_type method_name(){
return this;
}

Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}

class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}

public static void main(String args[]){


A5 obj=new A5();
System.out.println(obj);//prints the reference ID

obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java


For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Programmer salary is:40000.0


Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class.


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

Compile Time Error

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc.
It contains one more object named address, which contains its own informations such as city,
state, country, zipcode etc. as given below.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

Why use Aggregation?


For Code Reusability.
Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){


op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}

Output:78.5

When use Aggregation?


Code reuse is also best achieved by aggregation when there is no is-a relationship.
Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of
the objects involved; otherwise, aggregation is the best choice.
Understanding meaningful example of Aggregation
In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.

Address.java
public class Address {
String city,state,country;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}

Emp.java
public class Emp {
int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;
this.name = name;
this.address=address;
}

void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}

public static void main(String[] args) {


Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();

}
}

Output:111 varun
gzb UP india
112 arun
gno UP india

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


method must have same name as in the parent class
method must have same parameter as in the parent class.
must be IS-A relationship (inheritance).

Understanding the problem without method overriding


Let's understand the problem that we may face in the program if we don't use method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
}

Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}

Output:Bike is running safely

Real example of Java Method Overriding


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

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 Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

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

Can we override static method?


No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.

Why we cannot override static method?


because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.

Can we override java main method?


No, because main is a static method.

Covariant Return Type


The covariant return type specifies that the return type may vary in the same direction as the
subclass.
Before Java5, it was not possible to override any method by changing the return type. But now,
since Java5, it is possible to override method by changing the return type if subclass overrides
any method whose return type is Non-Primitive but it changes its return type to subclass type.
Let's take a simple example:

Note: If you are beginner to java, skip this topic and return to it after OOPs
concepts.

Simple example of Covariant Return Type


class A{
A get(){return this;}
}

class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}

public static void main(String args[]){


new B1().get().message();
}
}

Output:welcome to covariant return type


As you can see in the above example, the return type of the get() method of A class is A but the
return type of the get() method of B class is B. Both methods have different return type but it is
method overriding. This is known as covariant return type.

super keyword in java


The super keyword in java 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 java super Keyword


super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
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 Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
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 Bike4 extends Vehicle{


int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
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 Bike5 extends Vehicle{


Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();

}
}

Output:Vehicle is created
Bike is created

Note: 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 Bike6 extends Vehicle{


int speed;
Bike6(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike6 b=new Bike6(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 Student16 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[]){


Student16 s=new Student16();
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 Student17 extends Person{

void display(){
message();//will invoke parent class message() method
}

public static void main(String args[]){


Student17 s=new Student17();
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 Bike7{
int speed;

Bike7(){System.out.println("speed is "+speed);}

{speed=100;}
public static void main(String args[]){
Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}

Output:speed is 100
speed is 100

There are three places in java where you can perform operations:
method
constructor
block

What is invoked firstly instance initializer block or constructor?


class Bike8{
int speed;

Bike8(){System.out.println("constructor is invoked");}

{System.out.println("instance initializer block invoked");}

public static void main(String args[]){


Bike8 b1=new Bike8();
Bike8 b2=new Bike8();
}
}

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:
The instance initializer block is created when instance of the class is created.
The instance initializer block is invoked after the parent class constructor is invoked (i.e. after
super() constructor call).
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 B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B2 b=new B2();
}
}

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 B3 extends A{
B3(){
super();
System.out.println("child class constructor invoked");
}

B3(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[]){


B3 b1=new B3();
B3 b2=new B3(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 java final keyword can be used in
many context. Final can be:
variable
method
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) Java 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 Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error

2) Java 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) Java final class


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

Example of final class


final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 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 Honda2 extends Bike{
public static void main(String args[]){
new Honda2().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 Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}

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 Bike11{
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[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is 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 Java 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 Test3{
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

Java 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 Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}

Output:90
Java 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 BabyDog1 extends Dog{


public static void main(String args[]){
Animal a=new BabyDog1();
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
static binding (also known as early binding).
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.

Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java 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 has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.

1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple);//true
5. }
6. }

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 java instanceof operator

1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. System.out.println(d instanceof Animal);//true
7. }
8. }

Output:true

instanceof in java 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.

1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }

Output:false
Downcasting with java 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.

1. Dog d=new Animal();//Compilation error

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

1. Dog d=(Dog)new Animal();


2. //Compiles successfully but ClassCastException is thrown at runtime

Possibility of downcasting with instanceof


Let's see the example, where downcasting is possible by instanceof operator.

1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }

Output:ok downcasting performed

Downcasting without the use of java instanceof


Downcasting can also be performed without the use of instanceof operator as displayed in the
following example:

1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.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:

1. Animal a=new Animal();


2. Dog.method(a);
3. //Now ClassCastException but not in case of instanceof operator

Understanding Real use of instanceof in java


Let's see the real use of instanceof keyword by the example given below.

1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);
28. }
29. }

Output: b method

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java
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 in Java


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.

Example abstract class

1. abstract class A{}


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

Example abstract method

1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4.
5. class Honda4 extends Bike{
6. void run(){System.out.println("running safely..");}
7.
8. public static void main(String args[]){
9. Bike obj = new Honda4();
10. obj.run();
11. }
12. }

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.
File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class Circle1 extends Shape{
10. void draw(){System.out.println("drawing circle");}
11. }
12.
13. //In real scenario, method is called by programmer or user
14. class TestAbstraction1{
15. public static void main(String args[]){
16. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getSha
pe() method
17. s.draw();
18. }
19. }

drawing circle

Another example of abstract class in java


File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 7;}
7. }
8. class PNB extends Bank{
9. int getRateOfInterest(){return 7;}
10. }
11.
12. class TestBank{
13. public static void main(String args[]){
14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked
15. int interest=b.getRateOfInterest();
16. System.out.println("Rate of Interest is: "+interest+" %");
17. }}
Rate of Interest is: 7 %

Abstract class having constructor, data member, methods etc.


An abstract class can have data member, abstract method, method body, constructor and even
main() method.
File: TestAbstraction2.java

1. //example of abstract class that have method body


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7.
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. obj.run();
15. obj.changeGear();
16. }
17. }

bike is created
running safely..
gear changed

Rule: If there is any abstract method in a class, that class must be abstract.

1. class Bike12{
2. abstract void run();
3. }

compile time error


Rule: If you are extending any abstract 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.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}

Output:I am a
I am b
I am c
I am d
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java 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 Java interface
In this example, Printable interface have only one method, its implementation is provided in the
A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. obj.print();
11. }
12. }

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.
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. obj.print();
17. obj.show();
18. }
19. }

Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is


possible by 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:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestTnterface1 implements Printable,Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestTnterface1 obj = new TestTnterface1();
12. obj.print();
13. }
14. }

Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface .

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Hello
Welcome

Q) 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.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Nested Interface in Java


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:

1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non-
Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static
Interface has only static and final variables.
and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
5) Abstract class can provide the implementation Interface can't provide the implementation
of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

1. //Creating interface that has 4 methods


2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one method of A interface

10. abstract class B implements A{


11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the implementation of res
t of the methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}
Output:
I am a
I am b
I am c
I am d

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java 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 Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.

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

How to compile java package


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

1. javac -d directory javafilename

For example

1. 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 java package program


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.
1) 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.*

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }

Output:Hello

2) 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

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }

Output:Hello

3) 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

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

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 in java
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.java.bean or org.sssit.dao.
Example of Subpackage

1. package com.java.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }

To Compile: javac -d . Simple.java


To Run: java com.java.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:

1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. System.out.println("Welcome to package");
7. }
8. }

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
o By -classpath switch
● Permanent
o By setting the classpath in the environment variables
o 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.

1. //save as C.java otherwise Compilte Time Error


2.
3. class A{}
4. class B{}
5. 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:
1. //save as A.java
2.
3. package java;
4. public class A{}
1. //save as B.java
2.
3. package java;
4. public class B{}

Access Modifiers in java


There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java 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 access modifier


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. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

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. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

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

2) default access modifier


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. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

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 access modifier


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.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }

Output:Hello

4) public access modifier


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

Example of public access modifier

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }

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 Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Java access modifiers with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }

The default modifier is more restrictive than protected. That is why there is compile time error.

Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java 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.
The Java Bean class is the example of fully encapsulated class.

Advantage of Encapsulation in java


By providing only setter or getter method, you can make the class read-only or write-only.
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.

1. //save as Student.java
2. package com.java;
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10. this.name=name
11. }
12. }
1. //save as Test.java
2. package com.java;
3. class Test{
4. public static void main(String[] args){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }

Compile By: javac -d . Test.java


Run By: java com.java.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
returns the Class class object of this object. The
public final ClassgetClass() 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 creates and returns the exact copy (clone) of this
CloneNotSupportedException 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.
wakes up all the threads, waiting on this object's
public final void notifyAll()
monitor.
causes the current thread to wait for the specified
public final void wait(long timeout)throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).
causes the current thread to wait for the specified
public final void wait(long timeout,int
miliseconds and nanoseconds, until another thread
nanos)throws InterruptedException
notifies (invokes notify() or notifyAll() method).
causes the current thread to wait, until another
public final void wait()throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).
is invoked by the garbage collector before object is
protected void finalize()throws Throwable
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 generates
CloneNotSupportedException.
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

1. class Student18 implements Cloneable{


2. int rollno;
3. String name;
4.
5. Student18(int rollno,String name){
6. this.rollno=rollno;
7. this.name=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return super.clone();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student18 s1=new Student18(101,"amit");
17.
18. Student18 s2=(Student18)s1.clone();
19.
20. System.out.println(s1.rollno+" "+s1.name);
21. System.out.println(s2.rollno+" "+s2.name);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }

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.
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
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 set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java 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 Java 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 in java


There are two types of array.

● Single Dimensional Array


● Multidimensional Array

Single Dimensional Array in java

Syntax to Declare an Array in java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in java

1. 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.

1. class Testarray{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}

Output: 10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}

Output:33
3
4
5

Passing Array to method in java


We can pass the java array to 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.

1. class Testarray2{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array to method
15.
16. }}

Output:3

Multidimensional array in java


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

Syntax to Declare Multidimensional Array in java

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


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java

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

Example to initialize Multidimensional Array in java

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

Example of Multidimensional java array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. class Testarray3{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}

Output:1 2 3
2 4 5
4 4 5
What is the 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.

1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}

Output:I

Copying a java array


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

Syntax of arraycopy method

1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of arraycopy method

1. class TestArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }

Output:caffein
Addition of 2 matrices in java
Let's see a simple example that adds two matrices.

1. class Testarray5{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}

Output:2 6 8
6 8 10

Wrapper class in Java


Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into
primitive automatically. The automatic conversion of primitive into object is known and
autoboxing and vice-versa unboxing.
One of the eight classes of java.lang package are known as wrapper class in java. The list of
eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Wrapper class Example: Primitive to Wrapper

1. public class WrapperExample1{


2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer i=Integer.valueOf(a);//converting int into Integer
6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}

Output:
20 20 20

Wrapper class Example: Wrapper to Primitive

1. public class WrapperExample2{


2. public static void main(String args[]){
3. //Converting Integer to int
4. Integer a=new Integer(3);
5. int i=a.intValue();//converting Integer to int
6. int j=a;//unboxing, now compiler will write a.intValue() internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}

Output:
3 3 3

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:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }

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:

1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150

Java Strictfp Keyword


Java 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.

1. strictfp class A{}//strictfp applied on class


1. strictfp interface M{}//strictfp applied on interface
1. class A{
2. strictfp void m(){}//strictfp applied on method
3. }

Illegal code for strictfp keyword


The strictfp keyword cannot be applied on abstract methods, variables or constructors.

1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }

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.

1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }

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 java 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.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. 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.
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc

Difference between object and class


There are many differences between object and class. A list of differences between object and
class are given below:
No. Object Class
Class is a blueprint or
1) Object is an instance of a class. template from which objects
are created.
Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar
2)
keyboard, mouse, chair etc. objects.
3) Object is a physical entity. Class is a logical entity.
Class is declared using class
Object is created through new keyword mainly e.g.
4) keyword e.g.
Student s1=new Student();
class Student{}
5) Object is created many times as per requirement. Class is declared once.
Class doesn't allocated
6) Object allocates memory when it is created.
memory when it is created.
There are many ways to create object in java such as new There is only one way to
7) keyword, newInstance() method, clone() method, factory define class in java using
method and deserialization. class keyword.

Difference between method overloading and method


overriding in java
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
No. Method Overloading Method Overriding
Method overriding is used to provide
Method overloading is used to increase the the specific implementation of the
1)
readability of the program. method that is already provided by its
super class.
Method overriding occurs in two
2) Method overloading is performed within class. classes that have IS-A (inheritance)
relationship.
In case of method overloading, parameter must be In case of method overriding,
3)
different. parameter must be same.
Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return
Return type must be same or
5) type can be same or different in method
covariant in method overriding.
overloading. But you must have to change the
parameter.

Java Method Overloading example

1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }

Java String
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="java";

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.


The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable
class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in java and
how to create the string object.

What is String in java


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

How to create String object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

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 is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will return
the reference to the same instance.

Note: String objects are stored in a special memory area known as string
constant pool.

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(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).

Java String Example

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4.
5. char ch[]={'s','t','r','i','n','g','s'};
6. String s2=new String(ch);//converting char array to string
7.
8. String s3=new String("example");//creating java string by new keyword
9.
10. System.out.println(s1);
11. System.out.println(s2);
12. System.out.println(s3);
13. }}

java
strings
example

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
No. Method Description
returns char value for the particular
1 char charAt(int index)
index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
static String format(Locale l, String format, Object... returns formatted string with given
4
args) locale
returns substring for given begin
5 String substring(int beginIndex)
index
returns substring for given begin
6 String substring(int beginIndex, int endIndex)
index and end index
returns true or false after matching
7 boolean contains(CharSequence s)
the sequence of char value
static String join(CharSequence delimiter,
8 returns a joined string
CharSequence... elements)
static String join(CharSequence delimiter, Iterable<?
9 returns a joined string
extends CharSequence> elements)
checks the equality of string with
10 boolean equals(Object another)
object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
replaces all occurrences of specified
13 String replace(char old, char new)
char value
replaces all occurrences of specified
14 String replace(CharSequence old, CharSequence new)
CharSequence
returns trimmed string omitting
15 String trim()
leading and trailing spaces
16 String split(String regex) returns splitted string matching regex
returns splitted string matching regex
17 String split(String regex, int limit)
and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
returns specified char value index
20 int indexOf(int ch, int fromIndex)
starting with given index
21 int indexOf(String substring) returns specified substring index
returns specified substring index
22 int indexOf(String substring, int fromIndex)
starting with given index
23 String toLowerCase() returns string in lowercase.
returns string in lowercase using
24 String toLowerCase(Locale l)
specified locale.
25 String toUpperCase() returns string in uppercase.
returns string in uppercase using
26 String toUpperCase(Locale l)
specified locale.

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:

1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }

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:

1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }

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.

Java String compare

We can compare string in java 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 in java:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() method


The String 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.
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }

Output:true
true
false

1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s3));//true
8. }
9. }

Output:false
true

2) String compare by == operator


The = = operator compares references not values.

1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }

Output:true
false

3) String compare by compareTo() method


The String compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:

● s1 == s2 :0
● s1 > s2 :positive value
● s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }

Output:0
1
-1

String Concatenation in Java


In java, string concatenation forms a new string that is the combination of multiple strings.
There are two ways to concat string in java:

1. By + (string concatenation) operator


2. By concat() method

1) String Concatenation by + (string concatenation) operator


Java string concatenation operator (+) is used to add strings. For Example:

1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }

Output:Sachin Tendulkar
The Java compiler transforms above code to this:

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

In java, 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:

1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }

80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation
operator.
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string. Syntax:

1. public String concat(String another)

Let's see the example of String concat() method.

1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
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 is inclusive and endIndex is exclusive.

Note: Index starts from 0.


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: inclusive
● endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

1. String s="hello";
2. System.out.println(s.substring(0,2));//he

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

1. public class TestSubstring{


2. public static void main(String args[]){
3. String s="Sachin Tendulkar";
4. System.out.println(s.substring(6));//Tendulkar
5. System.out.println(s.substring(0,6));//Sachin
6. }
7. }

Tendulkar
Sachin
Java String class methods
The 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,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form
in window based, web based or mobile application.
Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)

SACHIN
sachin
Sachin

Java String trim() method


The string trim() method eliminates white spaces before and after string.

1. String s=" Sachin ";


2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin

Sachin
Sachin

Java String startsWith() and endsWith() method

1. String s="Sachin";
2. System.out.println(s.startsWith("Sa"));//true
3. System.out.println(s.endsWith("n"));//true

true
true
Java String charAt() method
The string charAt() method returns a character at specified index.

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

S
h

Java String length() method


The string length() method returns length of the string.

1. String s="Sachin";
2. System.out.println(s.length());//6

Java String 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.

1. String s=new String("Sachin");


2. String s2=s.intern();
3. System.out.println(s2);//Sachin

Sachin

Java String valueOf() method


The string valueOf() method coverts given type such as int, long, float, double, boolean, char and
char array into string.

1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);

Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.

1. String s1="Java is a programming language. Java is a platform. Java is an Island.";


2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "K
ava"
3. System.out.println(replaceString);

Output:
Kava is a programming language. Kava is a platform. Kava is an Island.

Java StringBuffer class


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

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important 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.

Important 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.

1) StringBuffer append() method


The append() method concatenates the given argument with this string.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

6) StringBuffer capacity() method


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.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
7) StringBuffer ensureCapacity() method
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.

1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Java StringBuilder class


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

Important 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.

Important methods of StringBuilder class


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

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this string.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuilder insert() method


The StringBuilder insert() method inserts the given string with this string at the given position.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuilder reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

6) StringBuilder capacity() method


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.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

7) StringBuilder ensureCapacity() method


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.

1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory when you StringBuffer is fast and consumes
2) concat too many strings because every time it creates less memory when you cancat
new instance. strings.
String class overrides the equals() method of Object StringBuffer class doesn't override
3) class. So you can compare the contents of two strings the equals() method of Object
by equals() method. class.
Performance Test of String and StringBuffer

1. public class ConcatTest{


2. public static String concatWithString() {
3. String t = "Java";
4. for (int i=0; i<10000; i++){
5. t = t + "Tpoint";
6. }
7. return t;
8. }
9. public static String concatWithStringBuffer(){
10. StringBuffer sb = new StringBuffer("Java");
11. for (int i=0; i<10000; i++){
12. sb.append("Tpoint");
13. }
14. return sb.toString();
15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(System.currentTimeMil
lis()-startTime)+"ms");
20. startTime = System.currentTimeMillis();
21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "+(System.currentT
imeMillis()-startTime)+"ms");
23. }
24. }

Time taken by Concating with String: 578ms


Time taken by Concating with StringBuffer: 0ms

String and StringBuffer HashCode Test


As you can see in the program given below, String returns new hashcode value when you concat
string but StringBuffer returns same.

1. public class InstanceTest{


2. public static void main(String args[]){
3. System.out.println("Hashcode test of String:");
4. String str="java";
5. System.out.println(str.hashCode());
6. str=str+"tpoint";
7. System.out.println(str.hashCode());
8.
9. System.out.println("Hashcode test of StringBuffer:");
10. StringBuffer sb=new StringBuffer("java");
11. System.out.println(sb.hashCode());
12. sb.append("tpoint");
13. System.out.println(sb.hashCode());
14. }
15. }

Hashcode test of String:


3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Difference between StringBuffer and StringBuilder


There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not
1) It means two threads can't call the methods thread safe. It means two threads can call the
of StringBuffer simultaneously. methods of StringBuilder simultaneously.
StringBuffer is less efficient than StringBuilder is more efficient than
2)
StringBuilder. StringBuffer.

StringBuffer Example

1. public class BufferTest{


2. public static void main(String[] args){
3. StringBuffer buffer=new StringBuffer("hello");
4. buffer.append("java");
5. System.out.println(buffer);
6. }
7. }

hellojava

StringBuilder Example

1. public class BuilderTest{


2. public static void main(String[] args){
3. StringBuilder builder=new StringBuilder("hello");
4. builder.append("java");
5. System.out.println(builder);
6. }
7. }

hellojava

Performance Test of StringBuffer and StringBuilder


Let's see the code to check the performance of StringBuffer and StringBuilder classes.

1. public class ConcatTest{


2. public static void main(String[] args){
3. long startTime = System.currentTimeMillis();
4. StringBuffer sb = new StringBuffer("Java");
5. for (int i=0; i<10000; i++){
6. sb.append("Tpoint");
7. }
8. System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() -
startTime) + "ms");
9. startTime = System.currentTimeMillis();
10. StringBuilder sb2 = new StringBuilder("Java");
11. for (int i=0; i<10000; i++){
12. sb2.append("Tpoint");
13. }
14. System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() -
startTime) + "ms");
15. }
16. }

Time taken by StringBuffer: 16ms


Time taken by StringBuilder: 0ms

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.
1. public final class Employee{
2. final String pancardNumber;
3.
4. public Employee(String pancardNumber){
5. this.pancardNumber=pancardNumber;
6. }
7.
8. public String getPancardNumber(){
9. return pancardNumber;
10. }
11.
12. }

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.

Java 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 Java 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.

1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19. }

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 Java toString() method


Now let's see the real example of toString() method.

1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }

Output:101 Raj lucknow


102 Vijay ghaziabad

StringTokenizer in Java
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
creates StringTokenizer with specified string and delimeter.
delim)
creates StringTokenizer with specified string, delimeter and
StringTokenizer(String str, String returnValue. If return value is true, delimiter characters are
delim, boolean returnValue) 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.

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer class

1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }

Output:Next token is : my

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


method of String class or regex (Regular Expression).

Java String charAt


The java string charAt() method returns a char value at the given index number. The index
number starts from 0.

Signature
The signature of string charAt() method is given below:

1. public char charAt(int index)

Parameter
index : index number, starts with 0
Returns
char value

Specified by
CharSequence interface

Throws
IndexOutOfBoundsException : if index is negative value or greater than this string length.

Java String charAt() method example

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="java";
4. char ch=name.charAt(4);//returns the char value at the 4th index
5. System.out.println(ch);
6. }}

Java String compareTo


The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
If first string is greater than second string, it returns positive number (difference of character
value). If first string is less than second string, it returns negative number and if first string is
equal to second string, it returns 0.

1. s1 > s2 => positive number


2. s1 < s2 => negative number
3. s1 == s2 => 0

Signature

1. public int compareTo(String anotherString)


Parameters
anotherString: represents string that is to be compared with current string

Returns
an integer value

Java String compareTo() method example

1. public class LastIndexOfExample{


2. public static void main(String args[]){
3. String s1="hello";
4. String s2="hello";
5. String s3="meklo";
6. String s4="hemlo";
7. System.out.println(s1.compareTo(s2));
8. System.out.println(s1.compareTo(s3));
9. System.out.println(s1.compareTo(s4));
10. }}

Output:
0
-5
-1

Java String concat


The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.

Signature
The signature of string concat() method is given below:

1. public String concat(String anotherString)

Parameter
anotherString : another string i.e. to be combined at the end of this string.
Returns
combined string

Java String concat() method example

1. public class ConcatExample{


2. public static void main(String args[]){
3. String s1="java string";
4. s1.concat("is immutable");
5. System.out.println(s1);
6. s1=s1.concat(" is immutable so assign it explicitly");
7. System.out.println(s1);
8. }}

java string
java string is immutable so assign it explicitly

Java String contains


The java string contains() method searches the sequence of characters in this string. It returns
true if sequence of char values are found in this string otherwise returns false.

Signature
The signature of string contains() method is given below:

1. public boolean contains(CharSequence sequence)

Parameter
sequence : specifies the sequence of characters to be searched.

Returns
true if sequence of char value exists, otherwise false.
Throws
NullPointerException : if sequence is null.

Java String contains() method example

1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}

true
true
false

Java String endsWith


The java string endsWith() method checks if this string ends with given suffix. It returns true if
this string ends with given suffix else returns false.

Signature
The syntax or signature of endsWith() method is given below.

1. public boolean endsWith(String suffix)

Parameter
suffix : Sequence of character

Returns
true or false

Java String endsWith() method example

1. public class EndsWithExample{


2. public static void main(String args[]){
3. String s1="java by java";
4. System.out.println(s1.endsWith("t"));
5. System.out.println(s1.endsWith("point"));
6. }}

Output:
true
true

Java String equals


The java string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it returns
true.
The String equals() method overrides the equals() method of Object class.

Signature

1. public boolean equals(Object anotherObject)

Parameter
anotherObject : another object i.e. compared with this string.

Returns
true if characters of both strings are equal otherwise false.

Overrides
equals() method of java Object class.

Java String equals() method example

1. public class EqualsExample{


2. public static void main(String args[]){
3. String s1="java";
4. String s2="java";
5. String s3="JAVA";
6. String s4="python";
7. System.out.println(s1.equals(s2));//true because content and case is same
8. System.out.println(s1.equals(s3));//false because case is not same
9. System.out.println(s1.equals(s4));//false because content is not same
10. }}

true
false
false

Java String format


The java string format() method returns the formatted string by given locale, format and
arguments.
If you don't specify the locale in String.format() method, it uses default locale by calling
Locale.getDefault() method.
The format() method of java language is like sprintf() function in c language and printf() method
of java language.

Signature
There are two type of string format() method:

1. public static String format(String format, Object... args)


2. and,
3. public static String format(Locale locale, String format, Object... args)

Parameters
locale : specifies the locale to be applied on the format() method.
format : format of the string.
args : arguments for the format string. It may be zero or more.

Returns
formatted string

Throws
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.

Java String format() method example

1. public class FormatExample{


2. public static void main(String args[]){
3. String name="sonoo";
4. String sf1=String.format("name is %s",name);
5. String sf2=String.format("value is %f",32.33434);
6. String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part fil
ling with 0
7.
8. System.out.println(sf1);
9. System.out.println(sf2);
10. System.out.println(sf3);
11. }}

name is sonoo
value is 32.334340
value is 32.334340000000

Java String getBytes()


The java string getBytes() method returns the byte array of the string. In other words, it returns
sequence of bytes.

Signature
There are 3 variant of getBytes() method. The signature or syntax of string getBytes() method is
given below:

1. public byte[] getBytes()


2. public byte[] getBytes(Charset charset)
3. public byte[] getBytes(String charsetName)throws UnsupportedEncodingException

Returns
sequence of bytes.

Java String getBytes() method example

1. public class StringGetBytesExample{


2. public static void main(String args[]){
3. String s1="ABCDEFG";
4. byte[] barr=s1.getBytes();
5. for(int i=0;i<barr.length;i++){
6. System.out.println(barr[i]);
7. }
8. }}

Output:
65
66
67
68
69
70
71

Java String indexOf


The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.

Signature
There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
No. Method Description
1 int indexOf(int ch) returns index position for the given char value
returns index position for the given char value and
2 int indexOf(int ch, int fromIndex)
from index
3 int indexOf(String substring) returns index position for the given substring
int indexOf(String substring, int returns index position for the given substring and
4
fromIndex) from index

Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string

Returns
index of the string
Java String indexOf() method example

1. public class IndexOfExample{


2. public static void main(String args[]){
3. String s1="this is index of example";
4. //passing substring
5. int index1=s1.indexOf("is");//returns the index of is substring
6. int index2=s1.indexOf("index");//returns the index of index substring
7. System.out.println(index1+" "+index2);//2 8
8.
9. //passing substring with from index
10. int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
11. System.out.println(index3);//5 i.e. the index of another is
12.
13. //passing char value
14. int index4=s1.indexOf('s');//returns the index of s char value
15. System.out.println(index4);//3
16. }}

2 8
5
3

Java String intern


The java string intern() method returns the interned string. It returns the canonical
representation of string.
It can be used to return string from pool memory, if it is created by new keyword.

Signature
The signature of intern method is given below:

1. public String intern()

Returns
interned string
Java String intern() method example

1. public class InternExample{


2. public static void main(String args[]){
3. String s1=new String("hello");
4. String s2="hello";
5. String s3=s1.intern();//returns string from pool, now it will be same as s2
6. System.out.println(s1==s2);//false because reference is different
7. System.out.println(s2==s3);//true because reference is same
8. }}

false
true

Java String isEmpty


The java string isEmpty() method checks if this string is empty. It returns true, if length of
string is 0 otherwise false.
The isEmpty() method of String class is included in java string since JDK 1.6.

Signature
The signature or syntax of string isEmpty() method is given below:

1. public boolean isEmpty()

Returns
true if length is 0 otherwise false.

Since
1.6

Java String isEmpty() method example

1. public class IsEmptyExample{


2. public static void main(String args[]){
3. String s1="";
4. String s2="java";
5.
6. System.out.println(s1.isEmpty());
7. System.out.println(s2.isEmpty());
8. }}

true
false

Java String join


The java string join() method returns a string joined with given delimiter. In string join method,
delimiter is copied for each elements.
In case of null element, "null" is added. The join() method is included in java string since JDK
1.8.
There are two types of join() methods in java string.

Signature
The signature or syntax of string join method is given below:

1. public static String join(CharSequence delimiter, CharSequence... elements)


2. and
3. public static String join(CharSequence delimiter, Iterable<? extends CharSequence> ele
ments)

Parameters
delimiter : char value to be added with each element
elements : char value to be attached with delimiter

Returns
joined string with delimiter

Throws
NullPointerException if element or delimiter is null.
Since
1.8

Java String join() method example

1. public class StringJoinExample{


2. public static void main(String args[]){
3. String joinString1=String.join("-","welcome","to","java");
4. System.out.println(joinString1);
5. }}

welcome-to-java

Java String lastIndexOf


The java string lastIndexOf() method returns last index of the given character value or
substring. If it is not found, it returns -1. The index counter starts from zero.

Signature
There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods are given
below:
No. Method Description
1 int lastIndexOf(int ch) returns last index position for the given char value
returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex)
and from index
3 int lastIndexOf(String substring) returns last index position for the given substring
int lastIndexOf(String substring, int returns last index position for the given substring
4
fromIndex) and from index

Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string

Returns
last index of the string
Java String lastIndexOf() method example

1. public class LastIndexOfExample{


2. public static void main(String args[]){
3. String s1="this is index of example";//there are 2 's' characters in this sentence
4. int index1=s1.lastIndexOf('s');//returns last index of 's' char value
5. System.out.println(index1);//6
6. }}

Output:
6

Java String length


The java string length() method length of the string. It returns count of total number of
characters. The length of java string is same as the unicode code units of the string.

Signature
The signature of the string length() method is given below:

1. public int length()

Specified by
CharSequence interface

Returns
length of characters

Java String length() method example

1. public class LengthExample{


2. public static void main(String args[]){
3. String s1="java";
4. String s2="python";
5. System.out.println("string length is: "+s1.length());//10 is the length of java string
6. System.out.println("string length is: "+s2.length());//6 is the length of python string
7. }}

string length is: 10


string length is: 6

Java String replace


The java string replace() method returns a string replacing all the old char or CharSequence to
new char or CharSequence.
Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char
values.

Signature
There are two type of replace methods in java string.

1. public String replace(char oldChar, char newChar)


2. and
3. public String replace(CharSequence target, CharSequence replacement)

The second replace method is added since JDK 1.5.

Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters

Returns
replaced string

Java String replace(char old, char new) method example

1. public class ReplaceExample1{


2. public static void main(String args[]){
3. String s1="java is a very good website";
4. String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
5. System.out.println(replaceString);
6. }}

jevetpoint is e very good website

Java String replace(CharSequence target, CharSequence replacement)


method example

1. public class ReplaceExample2{


2. public static void main(String args[]){
3. String s1="my name is khan my name is java";
4. String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
5. System.out.println(replaceString);
6. }}

my name was khan my name was java

Java String replaceAll


The java string replaceAll() method returns a string replacing all the sequence of characters
matching regex and replacement string.

Signature

1. public String replaceAll(String regex, String replacement)

Parameters
regex : regular expression
replacement : replacement sequence of characters

Returns
replaced string

Java String replaceAll() example: replace character


Let's see an example to replace all the occurrences of a single character.

1. public class ReplaceAllExample1{


2. public static void main(String args[]){
3. String s1="java is a very good website";
4. String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"
5. System.out.println(replaceString);
6. }}

jevetpoint is e very good website

Java String replaceAll() example: replace word


Let's see an example to replace all the occurrences of single word or set of words.

1. public class ReplaceAllExample2{


2. public static void main(String args[]){
3. String s1="My name is Khan. My name is Bob. My name is Sonoo.";
4. String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"
5. System.out.println(replaceString);
6. }}

My name was Khan. My name was Bob. My name was Sonoo.

Java String replaceAll() example: remove white spaces


Let's see an example to remove all the occurrences of white spaces.

1. public class ReplaceAllExample3{


2. public static void main(String args[]){
3. String s1="My name is Khan. My name is Bob. My name is Sonoo.";
4. String replaceString=s1.replaceAll("\\s","");
5. System.out.println(replaceString);
6. }}

MynamewasKhan.MynamewasBob.MynamewasSonoo.

Java String split


The java string split() method splits this string against given regular expression and returns a
char array.

Signature
There are two signature for split() method in java string.

1. public String split(String regex)


2. and,
3. public String split(String regex, int limit)
Parameter
regex : regular expression to be applied on string.
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.

Returns
array of strings

Throws
PatternSyntaxException if pattern for regular expression is invalid

Since
1.4

Java String split() method example


The given example returns total number of words in a string excluding space only. It also
includes special characters.

1. public class SplitExample{


2. public static void main(String args[]){
3. String s1="java string split method by java";
4. String[] words=s1.split("\\s");//splits the string based on string
5. //using java foreach loop to print elements of string array
6. for(String w:words){
7. System.out.println(w);
8. }
9. }}

java
string
split
method
by
java
Java String split() method with regex and length example

1. public class SplitExample2{


2. public static void main(String args[]){
3. String s1="welcome to split world";
4. System.out.println("returning words:");
5. for(String w:s1.split("\\s",0)){
6. System.out.println(w);
7. }
8. System.out.println("returning words:");
9. for(String w:s1.split("\\s",1)){
10. System.out.println(w);
11. }
12. System.out.println("returning words:");
13. for(String w:s1.split("\\s",2)){
14. System.out.println(w);
15. }
16.
17. }}

returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world

Java String startsWith


The java string startsWith() method checks if this string starts with given prefix. It returns true
if this string starts with given prefix else returns false.

Signature
The syntax or signature of startWith() method is given below.

1. public boolean startsWith(String prefix)


2. public boolean startsWith(String prefix, int offset)
Parameter
prefix : Sequence of character

Returns
true or false

Java String startsWith() method example

1. public class StartsWithExample{


2. public static void main(String args[]){
3. String s1="java string split method by java";
4. System.out.println(s1.startsWith("ja"));
5. System.out.println(s1.startsWith("java string"));
6. }}

Output:
true
true

Java String substring


The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where start
index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas
end index starts from 1.
There are two types of substring methods in java string.

Signature

1. public String substring(int startIndex)


2. and
3. public String substring(int startIndex, int endIndex)

If you don't specify endIndex, java substring() method will return all the characters from
startIndex.

Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive

Returns
specified string

Throws
StringIndexOutOfBoundsException if start index is negative value or end index is lower than
starting index.

Java String substring() method example

1. public class SubstringExample{


2. public static void main(String args[]){
3. String s1="java";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}

va
vatpoint

Java String toCharArray


The java string toCharArray() method converts this string into character array. It returns a
newly created character array, its length is similar to this string and its contents are initialized
with the characters of this string.

Signature
The signature or syntax of string toCharArray() method is given below:

1. public char[] toCharArray()

Returns
character array
Java String toCharArray() method example

1. public class StringToCharArrayExample{


2. public static void main(String args[]){
3. String s1="hello";
4. char[] ch=s1.toCharArray();
5. for(int i=0;i<ch.length;i++){
6. System.out.print(ch[i]);
7. }
8. }}

Output:
hello

Java String toLowerCase()


The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It
internally uses the default locale.

Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:

1. public String toLowerCase()


2. public String toLowerCase(Locale locale)

The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.

Returns
string in lowercase letter.

Java String toLowerCase() method example

1. public class StringLowerExample{


2. public static void main(String args[]){
3. String s1="JAVA HELLO stRIng";
4. String s1lower=s1.toLowerCase();
5. System.out.println(s1lower);
6. }}

Output:
java hello string

Java String toUpperCase


The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.
The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It
internally uses the default locale.

Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:

1. public String toUpperCase()


2. public String toUpperCase(Locale locale)

The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.

Returns
string in uppercase letter.

Java String toUpperCase() method example

1. public class StringUpperExample{


2. public static void main(String args[]){
3. String s1="hello string";
4. String s1upper=s1.toUpperCase();
5. System.out.println(s1upper);
6. }}

Output:
HELLO STRING
Java String trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before and
after the string, if it exists then removes the spaces and returns the omitted string.

The string trim() method doesn't omits middle spaces.

Signature
The signature or syntax of string trim method is given below:

1. public String trim()

Returns
string with omitted leading and trailing spaces

Java String trim() method example

1. public class StringTrimExample{


2. public static void main(String args[]){
3. String s1=" hello string ";
4. System.out.println(s1+"java");//without trim()
5. System.out.println(s1.trim()+"java");//with trim()
6. }}

hello string java


hello stringjava

Java String valueOf


The java string valueOf() method converts different types of values into string. By the help of
string valueOf() method, you can convert int to string, long to string, boolean to string, character
to string, float to string, double to string, object to string and char array to string.

Signature
The signature or syntax of string valueOf() method is given below:

1. public static String valueOf(boolean b)


2. public static String valueOf(char c)
3. public static String valueOf(char[] c)
4. public static String valueOf(int i)
5. public static String valueOf(long l)
6. public static String valueOf(float f)
7. public static String valueOf(double d)
8. public static String valueOf(Object o)

Returns
string representation of given value

Java String valueOf() method example

1. public class StringValueOfExample{


2. public static void main(String args[]){
3. int value=30;
4. String s1=String.valueOf(value);
5. System.out.println(s1+10);//concatenating string with 10
6. }}

Output:
3010

Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the Java
Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.

java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.

1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match operations
on a character sequence.
No. Method Description
1 boolean matches() test whether the regular expression matches the pattern.
2 boolean find() finds the next expression that matches the pattern.
boolean find(int finds the next expression that matches the pattern from the given start
3
start) number.

Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
No. Method Description
static Pattern compile(String compiles the given regex and return the instance of
1
regex) pattern.
Matcher matcher(CharSequence creates a matcher that matches the given input with
2
input) pattern.
It works as the combination of compile and matcher
static boolean matches(String
3 methods. It compiles the regular expression and
regex, CharSequence input)
matches the given input with the pattern.
splits the given input string around matches of given
4 String[] split(CharSequence input)
pattern.
5 String pattern() returns the regex pattern.

Example of Java Regular Expressions


There are three ways to write the regex example in java.

1. import java.util.regex.*;
2. public class RegexExample1{
3. public static void main(String args[]){
4. //1st way
5. Pattern p = Pattern.compile(".s");//. represents single character
6. Matcher m = p.matcher("as");
7. boolean b = m.matches();
8.
9. //2nd way
10. boolean b2=Pattern.compile(".s").matcher("as").matches();
11.
12. //3rd way
13. boolean b3 = Pattern.matches(".s", "as");
14.
15. System.out.println(b+" "+b2+" "+b3);
16. }}

Output
true true true

Regular Expression . Example


The . (dot) represents a single character.

1. import java.util.regex.*;
2. class RegexExample2{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
5. System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
6. System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
7. System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
8. System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
9. }}

Regex Character classes


No. Character Class Description
1 [abc] a, b, or c (simple class)
2 [^abc] Any character except a, b, or c (negation)
3 [a-zA-Z] a through z or A through Z, inclusive (range)
4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
5 [a-z&&[def]] d, e, or f (intersection)
6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Regular Expression Character classes Example

1. import java.util.regex.*;
2. class RegexExample3{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more
than once)
7. }}

Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
X? X occurs once or not at all
X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less than z times

Regular Expression Character classes and Quantifiers Example

1. import java.util.regex.*;
2. class RegexExample4{
3. public static void main(String args[]){
4. System.out.println("? quantifier ....");
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)

6. System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one ti


me)
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes
more than one time)
8. System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than on
e time)
9. System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come on
e time)
10.
11. System.out.println("+ quantifier ....");
12. System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more tim
es)
13. System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one ti
me)
14. System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes
more than once)
15. System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matchin
g pattern)
16.
17. System.out.println("* quantifier ....");
18. System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may co
me zero or more times)
19.
20. }}

Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex Description
. Any character (may or may not match terminator)
\d Any digits, short of [0-9]
\D Any non-digit, short for [^0-9]
\s Any whitespace character, short for [\t\n\x0B\f\r]
\S Any non-whitespace character, short for [^\s]
\w Any word character, short for [a-zA-Z_0-9]
\W Any non-word character, short for [^\w]
\b A word boundary
\B A non word boundary

Regular Expression Metacharacters Example

1. import java.util.regex.*;
2. class RegexExample5{
3. public static void main(String args[]){
4. System.out.println("metacharacters d....");\\d means digit
5.
6. System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)
7. System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)
8. System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than o
nce)
9. System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)
10.
11. System.out.println("metacharacters D....");\\D means non-digit
12.
13. System.out.println(Pattern.matches("\\D", "abc"));//false (non-
digit but comes more than once)
14. System.out.println(Pattern.matches("\\D", "1"));//false (digit)
15. System.out.println(Pattern.matches("\\D", "4443"));//false (digit)
16. System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)
17. System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)
18.
19. System.out.println("metacharacters D with quantifier....");
20. System.out.println(Pattern.matches("\\D*", "mak"));//true (non-
digit and may come 0 or more times)
21.
22. }}

Regular Expression Question 1

1. /*Create a regular expression that accepts alpha numeric characters only. Its
2. length must be 6 characters long only.*/
3.
4. import java.util.regex.*;
5. class RegexExample6{
6. public static void main(String args[]){
7. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true
8. System.out.println(Pattern.matches("[a-zA-Z0-
9]{6}", "kkvarun32"));//false (more than 6 char)
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true
10. System.out.println(Pattern.matches("[a-zA-Z0-
9]{6}", "arun$2"));//false ($ is not matched)
11. }}

Regular Expression Question 2

1. /*Create a regular expression that accepts 10 digit numeric characters


2. starting with 7, 8 or 9 only.*/
3.
4. import java.util.regex.*;
5. class RegexExample7{
6. public static void main(String args[]){
7. System.out.println("by character classes and quantifiers ...");
8. System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//true
9. System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));//true
10.
11. System.out.println(Pattern.matches("[789][0-
9]{9}", "99530389490"));//false (11 characters)
12. System.out.println(Pattern.matches("[789][0-
9]{9}", "6953038949"));//false (starts from 6)
13. System.out.println(Pattern.matches("[789][0-9]{9}", "8853038949"));//true
14.
15. System.out.println("by metacharacters ...");
16. System.out.println(Pattern.matches("[789]{1}\\d{9}", "8853038949"));//true
17. System.out.println(Pattern.matches("[789]{1}\\d{9}", "3853038949"));//false (starts fro
m 3)
18.
19. }}

Exception Handling in Java


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

What is 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.

What is exception handling


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. 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 statement will be executed. That is why we use exception handling in java.

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 Java 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
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 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.

1. 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.

1. String s=null;
2. 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.

1. String s="abc";
2. 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:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

Java try-catch

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw exception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

Problem without exception handling


Let's try to understand the problem if we don't use try-catch block.

1. public class Testtrycatch1{


2. public static void main(String args[]){
3. int data=50/0;//may throw exception
4. System.out.println("rest of the code...");
5. }
6. }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling


Let's see the solution of above problem by java try-catch block.

1. public class Testtrycatch2{


2. public static void main(String args[]){
3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }

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.
Internal working of java try-catch block

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.

Java catch multiple exceptions

Java Multi catch block


If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Let's see a simple example of java multi-catch block.
1. public class TestMultipleCatchBlock{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
9. catch(Exception e){System.out.println("common task completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }

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 .

1. class TestMultipleCatchBlock1{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }

Output:
Compile-time error

Java Nested try block


The try block within a try block is known as nested try block in java.
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:

1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....

Java nested try example


Let's see a simple example of java nested try block.

1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }

Java finally block


Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Note: If you don't handle exception, before terminating the program, JVM
executes finally block(if any).

Why use java finally

● Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Usage of Java finally


Let's see the different cases where java finally block can be used.

Case 1
Let's see the java finally example where exception doesn't occur.

1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Output:5
finally block is always executed
rest of the code...

Case 2
Let's see the java finally example where exception occurs and not handled.

1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3
Let's see the java finally example where exception occurs and handled.

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

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).

Java throw exception

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
1. throw exception;

Let's see the example of throw IOException.

1. throw new IOException("sorry device error);

java throw keyword example


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.

1. public class TestThrow1{


2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }

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

Java 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

1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }

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

1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }

Output:Compile Time Error

Java throws keyword


The Java 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 java throws

1. return_type method_name() throws exception_class_name{


2. //method code
3. }

Which exception should be declared


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 Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.

Java throws example


Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

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.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }

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

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:device operation performed


normal flow...

B)Program if exception occurs

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:Runtime Exception

Que) Can we rethrow an exception?


Yes, by throwing same exception in catch block.

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1)
throw an exception. exception.
2) Checked exception cannot be propagated Checked exception can be propagated with
using throw only. 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.
You can declare multiple exceptions e.g.
5) You cannot throw multiple exceptions. public void method()throws
IOException,SQLException.

Java throw example

1. void m(){
2. throw new ArithmeticException("sorry");
3. }

Java throws example

1. void m()throws ArithmeticException{


2. //method code
3. }

Java throw and throws example

1. void m()throws ArithmeticException{


2. throw new ArithmeticException("sorry");
3. }

Difference between final, finally and finalize


There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No. final finally finalize
Final is used to apply restrictions on Finally is used to place Finalize is used to
class, method and variable. Final class important code, it will be perform clean up
1) can't be inherited, final method can't be executed whether processing just before
overridden and final variable value can't exception is handled or object is garbage
be changed. not. collected.
2) Final is a keyword. Finally is a block. Finalize is a method.

Java final example

1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}

Java finally example

1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}

Java finalize example

1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();
9. }}

ExceptionHandling with MethodOverriding in Java


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


o 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.

1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild extends Parent{
7. void msg()throws IOException{
8. System.out.println("TestExceptionChild");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild();
12. p.msg();
13. }
14. }

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.

1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild1 extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild1();
12. p.msg();
13. }
14. }

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

1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild2 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild2();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }

Output:Compile Time Error

Example in case subclass overridden method declares same exception

1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild3 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild3();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }

Output:child

Example in case subclass overridden method declares subclass exception

1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild4 extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild4();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }

Output:child

Example in case subclass overridden method declares no exception

1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild5 extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild5();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception.

1. class InvalidAgeException extends Exception{


2. InvalidAgeException(String s){
3. super(s);
4. }
5. }
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }

Output:Exception occured: InvalidAgeException:not valid


rest of the code...

Java Inner Class


Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
Syntax of Inner class

1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:
1) 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.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) 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 ?

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 classes


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
o b)Annomynous inner class
o c)Local inner class
2. Static nested class

Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is
Class decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.

Java Member inner class


A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:

1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }

Java Member inner class example


In this example, we are creating msg() method in member inner class that is accessing the private
data member of outer class.

1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }

Output:
data is 30

Internal working of Java member inner class


The java compiler creates two class files in case of inner class. The class file name of inner class
is "Outer$Inner". If you want to instantiate inner class, you must have to create the instance of
outer class. In such case, instance of inner class is created inside the instance of outer class.
Internal code generated by the compiler
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.

1. import java.io.PrintStream;
2. class Outer$Inner
3. {
4. final Outer this$0;
5. Outer$Inner()
6. { super();
7. this$0 = Outer.this;
8. }
9. void msg()
10. {
11. System.out.println((new StringBuilder()).append("data is ")
12. .append(Outer.access$000(Outer.this)).toString());
13. }
14. }

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by two
ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }
Output:
nice fruits

Internal working of given code

1. Person p=new Person(){


2. void eat(){System.out.println("nice fruits");}
3. };
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 Anonymous class is created that is referred by p reference variable of
Person type.

Internal class generated by the compiler

1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }

Java anonymous inner class example using interface

1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }

Output:
nice fruits
Internal working of given code
It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };
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 Anonymous class is created that is referred by p reference variable of
Eatable type.

Internal class generated by the compiler

1. import java.io.PrintStream;
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
5. void eat(){System.out.println("nice fruits");}
6. }

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.

Java local inner class example

1. public class localInner1{


2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. }
14. }

Output:
30

Internal class generated by the compiler


In such case, compiler creates a class named Simple$1Local that have the reference of the outer
class.

1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }

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

Rules for Java Local Inner class

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

2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK
1.8, it is possible to access the non-final local variable in local inner class.

Example of local inner class with local variable

1. class localInner2{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final till jdk 1.7 only
5. class Local{
6. void msg(){System.out.println(value);}
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. localInner2 obj=new localInner2();
13. obj.display();
14. }
15. }

Output:
50

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.

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


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

Java static nested class example with instance method

1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }

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 class generated by the compiler

1. import java.io.PrintStream;
2. static class TestOuter1$Inner
3. {
4. TestOuter1$Inner(){}
5. void msg(){
6. System.out.println((new StringBuilder()).append("data is ")
7. .append(TestOuter1.data).toString());
8. }
9. }

Java static nested class example with static method


If you have the static member inside static nested class, you don't need to create instance of static
nested class.

1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }

Output:
data is 30

Java Nested Interface


An interface i.e. 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

1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
Syntax of nested interface which is declared within the class

1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }

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.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class TestNestedInterface1 implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new TestNestedInterface1();//upcasting here
13. message.msg();
14. }
15. }

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:.
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }

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.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class TestNestedInterface2 implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new TestNestedInterface2();//upcasting here
12. message.msg();
13. }
14. }

Output:hello nested interface

Can we define a class inside the interface?


Yes, 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:

1. interface M{
2. class A{}
3. }

Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

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 in java


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.
Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java 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 in java is controlled by JVM. The java 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:

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

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:

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }

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.

Thread Scheduler in Java


Thread scheduler in java 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 scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

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.

Sleep method in java


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

Syntax of sleep() method in java


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

Example of sleep method in java

1. class TestSleepMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. t1.start();
13. t2.start();
14. }
15. }

Output:
1
1
2
2
3
3
4
4
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 starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it
will throw exception.
Let's understand it by the example given below:

1. public class TestThreadTwice1 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestThreadTwice1 t1=new TestThreadTwice1();
7. t1.start();
8. t1.start();
9. }
10. }

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.

1. class TestCallRun1 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestCallRun1 t1=new TestCallRun1();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }

Output:running...
Problem if you direct call run() method

1. class TestCallRun2 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestCallRun2 t1=new TestCallRun2();
10. TestCallRun2 t2=new TestCallRun2();
11.
12. t1.run();
13. t2.run();
14. }
15. }

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
Example of join() method

1. class TestJoinMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. TestJoinMethod1 t1=new TestJoinMethod1();
12. TestJoinMethod1 t2=new TestJoinMethod1();
13. TestJoinMethod1 t3=new TestJoinMethod1();
14. t1.start();
15. try{
16. t1.join();
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }

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.
Example of join(long miliseconds) method

1. class TestJoinMethod2 extends Thread{


2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. TestJoinMethod2 t1=new TestJoinMethod2();
12. TestJoinMethod2 t2=new TestJoinMethod2();
13. TestJoinMethod2 t3=new TestJoinMethod2();
14. t1.start();
15. try{
16. t1.join(1500);
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }

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()
1. class TestJoinMethod3 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestJoinMethod3 t1=new TestJoinMethod3();
7. TestJoinMethod3 t2=new TestJoinMethod3();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }

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()
Example of currentThread() method

1. class TestJoinMethod4 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestJoinMethod4 t1=new TestJoinMethod4();
8. TestJoinMethod4 t2=new TestJoinMethod4();
9.
10. t1.start();
11. t2.start();
12. }
13. }

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:

1. class TestMultiNaming1 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestMultiNaming1 t1=new TestMultiNaming1();
7. TestMultiNaming1 t2=new TestMultiNaming1();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10.
11. t1.start();
12. t2.start();
13.
14. t1.setName("Sonoo Jaiswal");
15. System.out.println("After changing name of t1:"+t1.getName());
16. }
17. }

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:

1. class TestMultiNaming2 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestMultiNaming2 t1=new TestMultiNaming2();
8. TestMultiNaming2 t2=new TestMultiNaming2();
9.
10. t1.start();
11. t2.start();
12. }
13. }

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:

1. class TestMultiPriority1 extends Thread{


2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }

Output:running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Daemon Thread in Java


Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java

● 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?


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 Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description
public void setDaemon(boolean is used to mark the current thread as daemon thread or
1)
status) user thread.
2) public boolean isDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java


File: MyThread.java

1. public class TestDaemonThread1 extends Thread{


2. public void run(){
3. if(Thread.currentThread().isDaemon()){//checking for daemon thread
4. System.out.println("daemon thread work");
5. }
6. else{
7. System.out.println("user thread work");
8. }
9. }
10. public static void main(String[] args){
11. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new TestDaemonThread1();
14.
15. t1.setDaemon(true);//now t1 is daemon thread
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }

Output
daemon thread work
user thread work
user thread work

Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
File: MyThread.java

1. class TestDaemonThread2 extends Thread{


2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. TestDaemonThread2 t1=new TestDaemonThread2();
9. TestDaemonThread2 t2=new TestDaemonThread2();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }

Output:exception in thread main: java.lang.IllegalThreadStateException

Java Thread Pool


Java Thread pool represents a group of worker threads that are waiting for the job and reuse
many times.
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 Java Thread Pool
Better performance It saves time because there is no need to create new thread.

Real time usage


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 ExecutorService and Executors.
File: WorkerThread.java

1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){
6. this.message=s;
7. }
8. public void run() {
9. System.out.println(Thread.currentThread().getName()+" (Start) message = "+messa
ge);
10. processmessage();//call processmessage method that sleeps the thread for 2 secon
ds
11. System.out.println(Thread.currentThread().getName()+" (End)");//prints thread na
me
12. }
13. private void processmessage() {
14. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
15. }
16. }

File: JavaThreadPoolExample.java

1. public class TestThreadPool {


2. public static void main(String[] args) {
3. ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5
threads
4. for (int i = 0; i < 10; i++) {
5. Runnable worker = new WorkerThread("" + i);
6. executor.execute(worker);//calling execute method of ExecutorService
7. }
8. executor.shutdown();
9. while (!executor.isTerminated()) { }
10.
11. System.out.println("Finished all threads");
12. }
13. }

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

ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.


Java thread group is implemented by java.lang.ThreadGroup class.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.
No. Constructor Description
1) ThreadGroup(String name) creates a thread group with given name.
ThreadGroup(ThreadGroup parent, String creates a thread group with given parent group
2)
name) and name.
Important methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of important methods are given below.
No. Method Description
1) int activeCount() returns no. of threads running in current group.
2) int activeGroupCount() returns a no. of active group in this thread group.
3) void destroy() destroys this thread group and all its sub groups.
4) String getName() returns the name of this group.
5) ThreadGroup getParent() returns the parent of this group.
6) void interrupt() interrupts all threads of this group.
7) void list() prints information of this group to standard console.
Let's see a code to group multiple threads.

1. ThreadGroup tg1 = new ThreadGroup("Group A");


2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.

1. Thread.currentThread().getThreadGroup().interrupt();

ThreadGroup Example
File: ThreadGroupDemo.java

1. public class ThreadGroupDemo implements Runnable{


2. public void run() {
3. System.out.println(Thread.currentThread().getName());
4. }
5. public static void main(String[] args) {
6. ThreadGroupDemo runnable = new ThreadGroupDemo();
7. ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
8.
9. Thread t1 = new Thread(tg1, runnable,"one");
10. t1.start();
11. Thread t2 = new Thread(tg1, runnable,"two");
12. t2.start();
13. Thread t3 = new Thread(tg1, runnable,"three");
14. t3.start();
15.
16. System.out.println("Thread Group Name: "+tg1.getName());
17. tg1.list();
18.
19. }
20. }

Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]

Shutdown Hook
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts
down normally or abruptly. Performing clean resource means closing log file, sending some
alerts or something else. So if you want to execute some code before JVM shuts down, use
shutdown hook.

When does the JVM shut down?


The JVM shuts down when:

● user presses ctrl+c on the command prompt


● System.exit(int) method is invoked
● user logoff
● user shutdown etc.

The addShutdownHook(Runnable r) method


The addShutdownHook() method of Runtime class is used to register the thread with the Virtual
Machine. Syntax:

1. public void addShutdownHook(Runnable r){}

The object of Runtime class can be obtained by calling the static factory method getRuntime().
For example:
Runtime r = Runtime.getRuntime();

Factory method
The method that returns the instance of a class is known as factory method.
Simple example of Shutdown Hook

1. class MyThread extends Thread{


2. public void run(){
3. System.out.println("shut down hook task completed..");
4. }
5. }
6.
7. public class TestShutdown1{
8. public static void main(String[] args)throws Exception {
9.
10. Runtime r=Runtime.getRuntime();
11. r.addShutdownHook(new MyThread());
12.
13. System.out.println("Now main sleeping... press ctrl+c to exit");
14. try{Thread.sleep(3000);}catch (Exception e) {}
15. }
16. }

Output:Now main sleeping... press ctrl+c to exit


shut down hook task completed..

Note: The shutdown sequence can be stopped by invoking the halt(int) method
of Runtime class.

Same example of Shutdown Hook by annonymous class:

1. public class TestShutdown2{


2. public static void main(String[] args)throws Exception {
3.
4. Runtime r=Runtime.getRuntime();
5.
6. r.addShutdownHook(new Runnable(){
7. public void run(){
8. System.out.println("shut down hook task completed..");
9. }
10. }
11. );
12.
13. System.out.println("Now main sleeping... press ctrl+c to exit");
14. try{Thread.sleep(3000);}catch (Exception e) {}
15. }
16. }

Output:Now main sleeping... press ctrl+c to exit


shut down hook task completed..

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:
Program of performing single task by multiple threads

1. class TestMultitasking1 extends Thread{


2. public void run(){
3. System.out.println("task one");
4. }
5. public static void main(String args[]){
6. TestMultitasking1 t1=new TestMultitasking1();
7. TestMultitasking1 t2=new TestMultitasking1();
8. TestMultitasking1 t3=new TestMultitasking1();
9.
10. t1.start();
11. t2.start();
12. t3.start();
13. }
14. }

Output:task one
task one
task one
Program of performing single task by multiple threads

1. class TestMultitasking2 implements Runnable{


2. public void run(){
3. System.out.println("task one");
4. }
5.
6. public static void main(String args[]){
7. Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of Test
Multitasking2 class
8. Thread t2 =new Thread(new TestMultitasking2());
9.
10. t1.start();
11. t2.start();
12.
13. }
14. }

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:
Program of performing two tasks by two threads

1. class Simple1 extends Thread{


2. public void run(){
3. System.out.println("task one");
4. }
5. }
6.
7. class Simple2 extends Thread{
8. public void run(){
9. System.out.println("task two");
10. }
11. }
12.
13. class TestMultitasking3{
14. public static void main(String args[]){
15. Simple1 t1=new Simple1();
16. Simple2 t2=new Simple2();
17.
18. t1.start();
19. t2.start();
20. }
21. }

Output:task one
task two

Same example as above by annonymous class that extends Thread class:


Program of performing two tasks by two threads

1. class TestMultitasking4{
2. public static void main(String args[]){
3. Thread t1=new Thread(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8. Thread t2=new Thread(){
9. public void run(){
10. System.out.println("task two");
11. }
12. };
13.
14.
15. t1.start();
16. t2.start();
17. }
18. }
Output:task one
task two

Same example as above by annonymous class that implements Runnable


interface:
Program of performing two tasks by two threads

1. class TestMultitasking5{
2. public static void main(String args[]){
3. Runnable r1=new Runnable(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8.
9. Runnable r2=new Runnable(){
10. public void run(){
11. System.out.println("task two");
12. }
13. };
14.
15. Thread t1=new Thread(r1);
16. Thread t2=new Thread(r2);
17.
18. t1.start();
19. t2.start();
20. }
21. }

Output:task one
task two

Java Garbage Collection


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
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(a part of JVM) 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:

1. Employee e=new Employee();


2. e=null;

2) By assigning a reference to another:

1. Employee e1=new Employee();


2. Employee e2=new Employee();
3. 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 Object 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 in java

1. public class TestGarbage1{


2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }

object is garbage collected


object is garbage collected

Java Runtime class


Java Runtime class is used to interact with java runtime environment. Java Runtime class
provides methods to execute a process, invoke GC, get total and free memory etc. There is only
one instance of java.lang.Runtime class is available for one java application.
The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Important methods of Java Runtime class


No. Method Description
1) public static Runtime getRuntime() returns the instance of Runtime class.
2) public void exit(int status) terminates the current virtual machine.
3) public void addShutdownHook(Thread hook) registers new hook thread.
public Process exec(String command)throws executes given command in a separate
4)
IOException process.
5) public int availableProcessors() returns no. of available processors.
6) public long freeMemory() returns amount of free memory in JVM.
7) public long totalMemory() returns amount of total memory in JVM.

Java Runtime exec() method

1. public class Runtime1{


2. public static void main(String args[])throws Exception{
3. Runtime.getRuntime().exec("notepad");//will open a new notepad
4. }
5. }

Java Runtime freeMemory() and totalMemory() method


In the given program, after creating 10000 instance, free memory will be less than the previous
free memory. But after gc() call, you will get more free memory.

1. public class MemoryTest{


2. public static void main(String args[])throws Exception{
3. Runtime r=Runtime.getRuntime();
4. System.out.println("Total Memory: "+r.totalMemory());
5. System.out.println("Free Memory: "+r.freeMemory());
6.
7. for(int i=0;i<10000;i++){
8. new MemoryTest();
9. }
10. System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());
11. System.gc();
12. System.out.println("After gc(), Free Memory: "+r.freeMemory());
13. }
14. }

Total Memory: 100139008


Free Memory: 99474824
After creating 10000 instance, Free Memory: 99310552
After gc(), Free Memory: 100182832

Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
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.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

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

Concept of Lock in Java


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:

1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class TestSynchronization1{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output: 5
100
10
200
15
300
20
400
25
500

Java 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 thread completes its task.

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output: 5
10
15
20
25
100
200
300
400
500

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.

1. //Program of synchronized method by using annonymous class


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. public class TestSynchronization3{
15. public static void main(String args[]){
16. final Table obj = new Table();//only one object
17.
18. Thread t1=new Thread(){
19. public void run(){
20. obj.printTable(5);
21. }
22. };
23. Thread t2=new Thread(){
24. public void run(){
25. obj.printTable(100);
26. }
27. };
28.
29. t1.start();
30. t2.start();
31. }
32. }

Output: 5
10
15
20
25
100
200
300
400
500

Synchronized block in java


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

1. synchronized (object reference expression) {


2. //code block
3. }

Example of synchronized block


Let's see the simple example of synchronized block.
Program of synchronized block

1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }

Output:5
10
15
20
25
100
200
300
400
500

Same Example of synchronized block by using annonymous class:


//Program of synchronized block by using annonymous class

1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. public class TestSynchronizedBlock2{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29.
30. t1.start();
31. t2.start();
32. }
33. }

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.

1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30.
31.
32.
33.
34. class MyThread4 extends Thread{
35. public void run(){
36. Table.printTable(1000);
37. }
38. }
39.
40. public class TestSynchronization4{
41. public static void main(String t[]){
42. MyThread1 t1=new MyThread1();
43. MyThread2 t2=new MyThread2();
44. MyThread3 t3=new MyThread3();
45. MyThread4 t4=new MyThread4();
46. t1.start();
47. t2.start();
48. t3.start();
49. t4.start();
50. }
51. }

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.

1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class TestSynchronization5 {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }

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:

1. static void printTable(int n) {


2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }

Deadlock in java
Deadlock in java is a part of multithreading. 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

1. public class TestDeadlockExample1 {


2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);} catch (Exception e) {}
12.
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24. System.out.println("Thread 2: locked resource 2");
25.
26. try { Thread.sleep(100);} catch (Exception e) {}
27.
28. synchronized (resource1) {
29. System.out.println("Thread 2: locked resource 1");
30. }
31. }
32. }
33. };
34.
35.
36. t1.start();
37. t2.start();
38. }
39. }
40.

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 waits for the specified amount of
InterruptedException 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() after the specified amount of time, sleep is
methods completed.

Example of inter thread communication in java


Let's see the simple example of inter thread communication.

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
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.
1. class TestInterruptingThread1 extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. throw new RuntimeException("Thread interrupted..."+e);
8. }
9.
10. }
11.
12. public static void main(String args[]){
13. TestInterruptingThread1 t1=new TestInterruptingThread1();
14. t1.start();
15. try{
16. t1.interrupt();
17. }catch(Exception e){System.out.println("Exception handled "+e);}
18.
19. }
20. }

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.
1. class TestInterruptingThread2 extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. System.out.println("Exception handled "+e);
8. }
9. System.out.println("thread is running...");
10. }
11.
12. public static void main(String args[]){
13. TestInterruptingThread2 t1=new TestInterruptingThread2();
14. t1.start();
15.
16. t1.interrupt();
17.
18. }
19. }

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.
1. class TestInterruptingThread3 extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=5;i++)
5. System.out.println(i);
6. }
7.
8. public static void main(String args[]){
9. TestInterruptingThread3 t1=new TestInterruptingThread3();
10. t1.start();
11.
12. t1.interrupt();
13.
14. }
15. }

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.
1. public class TestInterruptingThread4 extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=2;i++){
5. if(Thread.interrupted()){
6. System.out.println("code for interrupted thread");
7. }
8. else{
9. System.out.println("code for normal thread");
10. }
11.
12. }//end of for loop
13. }
14.
15. public static void main(String args[]){
16.
17. TestInterruptingThread4 t1=new TestInterruptingThread4();
18. TestInterruptingThread4 t2=new TestInterruptingThread4();
19.
20. t1.start();
21. t1.interrupt();
22.
23. t2.start();
24.
25. }
26. }

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:

1. class Reentrant {
2. public synchronized void m() {
3. n();
4. System.out.println("this is m() method");
5. }
6. public synchronized void n() {
7. System.out.println("this is n() method");
8. }
9. }

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.

1. public class ReentrantExample{


2. public static void main(String args[]){
3. final ReentrantExample re=new ReentrantExample();
4.
5. Thread t1=new Thread(){
6. public void run(){
7. re.m();//calling method of Reentrant class
8. }
9. };
10. t1.start();
11. }}

Output: this is n() method


this is m() method

Java I/O Tutorial


Java I/O (Input and Output) is used to process the input and produce the output based on the
input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in java by java IO API.

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.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

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.

Let's understand working of Java OutputStream and InputStream by the figure given below.

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
is used to write a byte to the current output stream.
IOException:
2) public void write(byte[])throws is used to write an array of byte to the current
IOException: 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 reads the next byte of data from the input stream.It returns
IOException: -1 at the end of file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException: read from the current input stream.
3) public void close()throws
is used to close the current input stream.
IOException:
FileInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.

Java FileOutputStream class


Java FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented
data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.

Example of Java FileOutputStream class

1. import java.io.*;
2. class Test{
3. public static void main(String args[]){
4. try{
5. FileOutputstream fout=new FileOutputStream("abc.txt");
6. String s="Sachin Tendulkar is my favourite player";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){system.out.println(e);}
12. }
13. }
Output:success...

Java FileInputStream class


Java FileInputStream class 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, audio, video etc.

Example of FileInputStream class

1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("abc.txt");
6. int i=0;
7. while((i=fin.read())!=-1){
8. System.out.println((char)i);
9. }
10. fin.close();
11. }catch(Exception e){system.out.println(e);}
12. }
13. }

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.

1. import java.io.*;
2. class C{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin=new FileInputStream("C.java");
5. FileOutputStream fout=new FileOutputStream("M.java");
6. int i=0;
7. while((i=fin.read())!=-1){
8. fout.write((byte)i);
9. }
10. fin.close();
11. }
12. }

Java ByteArrayOutputStream class


Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the
data is written into a byte array that can be written to multiple stream.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.

Closing the ByteArrayOutputStream has no effect.

Constructors of ByteArrayOutputStream class


Constructor Description
creates a new byte array output stream with the initial capacity
ByteArrayOutputStream()
of 32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int creates a new byte array output stream, with a buffer capacity of
size) the specified size, in bytes.

Methods of ByteArrayOutputStream class


Method Description
1) public synchronized void
writes the complete contents of this byte array
writeTo(OutputStream out) throws
output stream to the specified output stream.
IOException
2) public void write(byte b) throws
writes byte into this stream.
IOException
3) public void write(byte[] b) throws
writes byte array into this stream.
IOException
4) public void flush() flushes this stream.
has no affect, it doesn't closes the
5) public void close()
bytearrayoutputstream.

Java ByteArrayOutputStream Example


Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.

1. import java.io.*;
2. class S{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("f1.txt");
5. FileOutputStream fout2=new FileOutputStream("f2.txt");
6.
7. ByteArrayOutputStream bout=new ByteArrayOutputStream();
8. bout.write(139);
9. bout.writeTo(fout1);
10. bout.writeTo(fout2);
11.
12. bout.flush();
13. bout.close();//has no effect
14. System.out.println("success...");
15. }
16. }

success...
Java SequenceInputStream class
Java SequenceInputStream class is used to read data from multiple streams. It reads data of
streams one by one.

Constructors of SequenceInputStream class:


Constructor Description
1) SequenceInputStream(InputStream s1, creates a new input stream by reading the data
InputStream s2) of two input stream in order, first s1 and then s2.
creates a new input stream by reading the data
2) SequenceInputStream(Enumeration e)
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.

1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileinputStream fin1=new FileinputStream("f1.txt");
5. FileinputStream fin2=new FileinputStream("f2.txt");
6.
7. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
8. int i;
9. while((i=sis.read())!=-1){
10. System.out.println((char)i);
11. }
12. sis.close();
13. fin1.close();
14. fin2.close();
15. }
16. }

Example of SequenceInputStream that reads the data from two files


In this example, we are writing the data of two files f1.txt and f2.txt into another file named
f3.txt.

1. //reading data of 2 files and writing it into one file


2.
3. import java.io.*;
4. class Simple{
5. public static void main(String args[])throws Exception{
6.
7. FileinputStream fin1=new FileinputStream("f1.txt");
8. FileinputStream fin2=new FileinputStream("f2.txt");
9.
10. FileOutputStream fout=new FileOutputStream("f3.txt");
11.
12. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
13. int i;
14. while((i.sisread())!=-1)
15. {
16. fout.write(i);
17. }
18. sis.close();
19. fout.close();
20. fin.close();
21. fin.close();
22.
23. }
24. }

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.
1. import java.io.*;
2. import java.util.*;
3.
4. class B{
5. public static void main(String args[])throws IOException{
6.
7. //creating the FileInputStream objects for all the files
8. FileInputStream fin=new FileInputStream("A.java");
9. FileInputStream fin2=new FileInputStream("abc2.txt");
10. FileInputStream fin3=new FileInputStream("abc.txt");
11. FileInputStream fin4=new FileInputStream("B.java");
12.
13. //creating Vector object to all the stream
14. Vector v=new Vector();
15. v.add(fin);
16. v.add(fin2);
17. v.add(fin3);
18. v.add(fin4);
19.
20. //creating enumeration object by calling the elements method
21. Enumeration e=v.elements();
22.
23. //passing the enumeration object in the constructor
24. SequenceInputStream bin=new SequenceInputStream(e);
25. int i=0;
26.
27. while((i=bin.read())!=-1){
28. System.out.print((char)i);
29. }
30.
31. bin.close();
32. fin.close();
33. fin2.close();
34. }
35. }

Java BufferedOutputStream and BufferedInputStream

Java BufferedOutputStream class


Java BufferedOutputStream class uses an internal buffer to store data. 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.

1. import java.io.*;
2. class Test{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("f1.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Sachin is my favourite player";
7. byte b[]=s.getBytes();
8. bout.write(b);
9.
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }

Output:
success...

Java BufferedInputStream class


Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.

Example of Java BufferedInputStream


Let's see the simple example to read data of file using BufferedInputStream.

1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("f1.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.println((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }

Output:
Sachin is my favourite player

Java FileWriter and FileReader (File Handling in java)


Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to
read and write the textual information.

Java FileWriter class


Java FileWriter class is used to write character-oriented data to the file.

Constructors of FileWriter class


Constructor Description
FileWriter(String file) creates a new file. It gets file name in string.
FileWriter(File file) creates a new file. It gets file name in File object.

Methods of FileWriter class


Method Description
1) public void write(String text) writes the string into FileWriter.
2) public void write(char c) writes the char into FileWriter.
3) public void write(char[] c) writes char array into FileWriter.
4) public void flush() flushes the data of FileWriter.
5) public void close() closes FileWriter.

Java FileWriter Example


In this example, we are writing the data in the file abc.txt.

1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("success");
10. }
11. }

Output:
success...

Java FileReader class


Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.

Constructors of FileWriter class


Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't
file) exist, it throws FileNotFoundException.
It gets filename in file instance. It opens the given file in read mode. If file
FileReader(File file)
doesn't exist, it throws FileNotFoundException.

Methods of FileReader class


Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the end of file.
2) public void close() closes FileReader.

Java FileReader Example


In this example, we are reading the data from the file abc.txt file.

1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("abc.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.println((char)i);
8.
9. fr.close();
10. }
11. }

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.

1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }

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 InputStreamReader
stream for reading the line by line data from the keyboard.

1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. System.out.println("Enter your name");
9. String name=br.readLine();
10. System.out.println("Welcome "+name);
11. }
12. }

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.

1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while(!name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }

Output:Enter data: Amit


data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop

Java Console class


The Java Console class is be used to get input from console. It provides methods to read text and
password.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
Let's see a simple example to read text from console.

1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Methods of Console class
Let's see the commonly used methods of Console class.
Method Description
1) public String readLine() is used to read a single line of text from the console.
2) public String readLine(String it provides a formatted prompt then reads the single line
fmt,Object... args) of text from the console.
is used to read password that is not being displayed on
3) public char[] readPassword()
the console.
4) public char[] readPassword(String it provides a formatted prompt then reads the password
fmt,Object... args) that is not being displayed on the console.

How to get the object of Console


System class provides a static method console() that returns the unique instance of Console class.

1. public static Console console(){}

Let's see the code to get the instance of Console class.

1. Console c=System.console();

Java Console Example

1. import java.io.*;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }

Output:
Enter your name: james gosling
Welcome james gosling

Java Console Example to read password

1. import java.io.*;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }

Output:
Enter password:
Password is: sonoo

Java Scanner class


There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class


There is a list of commonly used Scanner class methods:
Method Description
public String next() it returns the next token from the scanner.
it moves the scanner position to the next line and returns the value as
public String nextLine()
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
it scans the next token as a double value.
nextDouble()

Java Scanner Example to get input from console


Let's see the simple example of the Java Scanner class which reads the int, string and double
value as an input:

1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }

Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter


Let's see the example of Scanner class with delimiter. The \s represents whitespace.

1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}

Output:
10
tea
20
coffee
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.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }

Example of printf() method of java.io.PrintStream class:


Let's see the simple example of printing integer value by format specifier.
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=10;
4. System.out.printf("%d",a);//Note, out is the object of PrintStream class
5.
6. }
7. }

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

1. import java.io.*;
2. import java.util.zip.*;
3.
4. class Compress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("Deflater.java");
9.
10. FileOutputStream fout=new FileOutputStream("def.txt");
11. DeflaterOutputStream out=new DeflaterOutputStream(fout);
12.
13. int i;
14. while((i=fin.read())!=-1){
15. out.write((byte)i);
16. out.flush();
17. }
18.
19. fin.close();
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. System.out.println("rest of the code");
24. }
25. }

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 class


In this example, we are decompressing the compressed file def.txt into D.java .

1. import java.io.*;
2. import java.util.zip.*;
3.
4. class UnCompress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("def.txt");
9. InflaterInputStream in=new InflaterInputStream(fin);
10.
11. FileOutputStream fout=new FileOutputStream("D.java");
12.
13. int i;
14. while((i=in.read())!=-1){
15. fout.write((byte)i);
16. fout.flush();
17. }
18.
19. fin.close();
20. fout.close();
21. in.close();
22.
23. }catch(Exception e){System.out.println(e);}
24. System.out.println("rest of the code");
25. }
26. }

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.

1. import java.io.*;
2. class PipedWR{
3. public static void main(String args[])throws Exception{
4. final PipedOutputStream pout=new PipedOutputStream();
5. final PipedInputStream pin=new PipedInputStream();
6.
7. pout.connect(pin);//connecting the streams
8. //creating one thread t1 which writes the data
9. Thread t1=new Thread(){
10. public void run(){
11. for(int i=65;i<=90;i++){
12. try{
13. pout.write(i);
14. Thread.sleep(1000);
15. }catch(Exception e){}
16. }
17. }
18. };
19. //creating another thread t2 which reads the data
20. Thread t2=new Thread(){
21. public void run(){
22. try{
23. for(int i=65;i<=90;i++)
24. System.out.println(pin.read());
25. }catch(Exception e){}
26. }
27. };
28. //starting both threads
29. t1.start();
30. t2.start();
31. }}
Serialization in Java
Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantage of Java Serialization


It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface
Serializable is a marker interface (has 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:

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

ObjectOutputStream class
The ObjectOutputStream class 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.

Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an
ObjectOutputStream that writes to the specified OutputStream.

Important Methods
Method Description
1) public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.

Example of Java 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.

1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi");
5.
6. FileOutputStream fout=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(fout);
8.
9. out.writeObject(s1);
10. out.flush();
11. System.out.println("success");
12. }
13. }

success

Deserialization in java
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.

Constructor
1) public ObjectInputStream(InputStream in) creates an ObjectInputStream that reads
throws IOException {} from the specified InputStream.

Important Methods
Method Description
1) public final Object readObject() throws IOException, reads an object from the input
ClassNotFoundException{} stream.
2) public void close() throws IOException {} closes ObjectInputStream.

Example of Java Deserialization

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }

211 ravi

Java Serialization with Inheritance (IS-A Relationship)


If a class implements serializable then all its sub classes will also be serializable. Let's see the
example given below:

1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
1. class Student extends Person{
2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fee;
8. }
9. }

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.

Java Serialization with Aggregation (HAS-A Relationship)


If a class has a reference of another class, all the references must be Serializable otherwise
serialization process will not be performed. In such case, NotSerializableException is thrown at
runtime.

1. class Address{
2. String addressLine,city,state;
3. public Address(String addressLine, String city, String state) {
4. this.addressLine=addressLine;
5. this.city=city;
6. this.state=state;
7. }
8. }
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. Address address;//HAS-A
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }

Since Address is not Serializable, you can not serialize the instance of Student class.

Note: All the objects within an object must be Serializable.

Java Serialization with static data member


If there is any static data member in a class, it will not be serialized because static is the part of
class not object.

1. class Employee implements Serializable{


2. int id;
3. String name;
4. static String company="SSS IT Pvt Ltd";//it won't be serialized
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

Java Serialization with array or collection


Rule: In case of array or collection, all the objects of array or collection must be serializable. If
any object is not serialiizable, serialization will be failed.

Externalizable in java
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

Java Transient Keyword


If you don't want to serialize any data member of a class, you can mark it as transient.
Visit next page for more details.

Java Transient Keyword


Java 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 data member as transient.

Example of Java Transient Keyword


In this example, we have created the two classes Student and PersistExample. The age data
member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. transient int age;//Now it will not be serialized
6. public Student(int id, String name,int age) {
7. this.id = id;
8. this.name = name;
9. this.age=age;
10. }
11. }

Now write the code to serialize the object.

1. import java.io.*;
2. class PersistExample{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi",22);//creating object
5. //writing object into file
6. FileOutputStream f=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(f);
8. out.writeObject(s1);
9. out.flush();
10.
11. out.close();
12. f.close();
13. System.out.println("success");
14. }
15. }

Output:
success
Now write the code for deserialization.

1. import java.io.*;
2. class DePersist{
3. public static void main(String args[])throws Exception{
4. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
5. Student s=(Student)in.readObject();
6. System.out.println(s.id+" "+s.name+" "+s.age);
7. in.close();
8. }
9. }

211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking

1. sharing resources
2. centralize software management

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 ?

Java Networking Terminology


The widely used java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:

● TCP
● FTP
● Telnet
● SMTP
● POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.

4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two way communication.
Visit next page for java socket programming.
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)

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Important methods
Method Description
returns the socket and establish a connection between server
1) public Socket accept()
and client.
2) public synchronized void
closes the server socket.
close()

Example of Java Socket Programming


Let's see a simple of java socket programming in which client sends a text and server receives it.
File: MyServer.java

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

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

To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java

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

File: MyClient.java

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

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:

1. http://www.java.com/java-tutorial

A URL contains many information:

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


2. Server name or IP Address: In this case, www.java.com is the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.java.com:80/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Commonly used methods of Java URL class


The java.net.URL class provides many methods. The important methods of URL class are given
below.
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection it returns the instance of URLConnection i.e. associated
openConnection() with this URL.

Example of Java URL class

1. //URLDemo.java
2. import java.io.*;
3. import java.net.*;
4. public class URLDemo{
5. public static void main(String[] args){
6. try{
7. URL url=new URL("http://www.java.com/java-tutorial");
8.
9. System.out.println("Protocol: "+url.getProtocol());
10. System.out.println("Host Name: "+url.getHost());
11. System.out.println("Port Number: "+url.getPort());
12. System.out.println("File Name: "+url.getFile());
13.
14. }catch(Exception e){System.out.println(e);}
15. }
16. }

Output:
Protocol: http
Host Name: www.java.com
Port Number: -1
File Name: /java-tutorial

Java URLConnection class


The Java 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:

1. public URLConnection openConnection()throws IOException{}

Displaying source code of a webpage by URLConnecton class


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

Example of Java URLConnecton class

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

Java HttpURLConnection class


The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
By the help of HttpURLConnection class, you can information of any HTTP URL such as header
information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.

How to get the object of HttpURLConnection class


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

1. public URLConnection openConnection()throws IOException{}

You can typecast it to HttpURLConnection type as given below.

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


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

Java HttpURLConnecton Example

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

Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.java.com, www.google.com,
www.facebook.com etc.

Commonly used methods of InetAddress class


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

Example of Java InetAddress class


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

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

Output:
Host Name: www.java.com
IP Address: 206.51.231.148

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.

Commonly used Constructors of DatagramSocket class

● DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with


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

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it
may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

● DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor


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

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

Example of Receiving DatagramPacket by DatagramSocket

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

Java AWT Tutorial


Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
application in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources of system.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.

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 such as
Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. 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 menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class


Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager
defines the layout manager for the component.
m)
changes the visibility of the component, by default
public void setVisible(boolean status)
false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

● By extending Frame class (inheritance)


● By creating the object of Frame class (association)

Simple example of AWT by inheritance

1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6.
7. add(b);//adding button into frame
8. setSize(300,300);//frame size 300 width and 300 height
9. setLayout(null);//no layout manager
10. setVisible(true);//now frame will be visible, by default not visible
11. }
12. public static void main(String args[]){
13. First f=new First();
14. }}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.

Simple example of AWT by association

1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5.
6. Button b=new Button("click me");
7. b.setBounds(30,50,80,30);
8.
9. f.add(b);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13. }
14. public static void main(String args[]){
15. First2 f=new First2();
16. }}

Event and Listener (Java 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 Event Handling


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 public void addActionListener(ActionListener a){}
● MenuItem
o public void addActionListener(ActionListener a){}
● TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
● TextArea
o public void addTextListener(TextListener a){}
● Checkbox
o public void addItemListener(ItemListener a){}
● Choice
o public void addItemListener(ItemListener a){}
● List
o public void addActionListener(ActionListener a){}
o 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:

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. class AEvent extends Frame implements ActionListener{
5. TextField tf;
6. AEvent(){
7.
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10.
11. Button b=new Button("click me");
12. b.setBounds(100,120,80,30);
13.
14. b.addActionListener(this);
15.
16. add(b);add(tf);
17.
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21.
22. }
23.
24. public void actionPerformed(ActionEvent e){
25. tf.setText("Welcome");
26. }
27.
28. public static void main(String args[]){
29. new AEvent();
30. }
31. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.

2) Example of event handling by Outer class:

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6.
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9.
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. Outer o=new Outer(this);
14. b.addActionListener(o);//passing outer class instance
15.
16. add(b);add(tf);
17.
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public static void main(String args[]){
23. new AEvent2();
24. }
25. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

3) Example of event handling by Annonymous class:

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }

Java Swing Tutorial


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
Java swing components are platform-
1) AWT components are platform-dependent.
independent.
2) AWT components are heavyweight. Swing components are lightweight.
Swing supports pluggable look and
3) AWT doesn't support pluggable look and feel.
feel.
Swing provides more powerful
components such as tables, lists,
4) AWT provides less components than Swing.
scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows MVC(Model View Controller)
where model represents data, view represents
5) Swing follows MVC.
presentation and controller acts as an interface
between model and view.

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 create runnable jar file in java?


● 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 Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
sets the visibility of the component. It is by default
public void setVisible(boolean b)
false.

Java Swing Examples


There are two ways to create a frame:

● By creating the object of Frame class (association)


● By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java

1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}

What we will learn in Swing Tutorial

● JButton class
● JRadioButton class
● JTextArea class
● JComboBox class
● JTable class
● JColorChooser class
● JProgressBar class
● JSlider class
● Digital Watch
● Graphics in swing
● Displaying image
● Edit menu code for Notepad
● OpenDialog Box
● Notepad
● Puzzle Game
● Pic Puzzle Game
● Tic Tac Toe Game
● BorderLayout
● GridLayout
● FlowLayout
● CardLayout

JButton class:
The JButton class is used to create a button that have plateform-independent implementation.

Commonly used Constructors:

● JButton(): creates a button with no text and icon.


● JButton(String s): creates a button with the specified text.
● JButton(Icon i): creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this
object.

Note: The JButton class extends AbstractButton class.

Example of displaying image on the button:

1. import java.awt.event.*;
2. import javax.swing.*;
3.
4. public class ImageButton{
5. ImageButton(){
6. JFrame f=new JFrame();
7.
8.
9. JButton b=new JButton(new ImageIcon("b.jpg"));
10. b.setBounds(130,100,100, 40);
11.
12. f.add(b);
13.
14. f.setSize(300,400);
15. f.setLayout(null);
16. f.setVisible(true);
17.
18. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19.
20. }
21.
22. public static void main(String[] args) {
23. new ImageButton();
24. }
25. }

JRadioButton class
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.

Commonly used Constructors of JRadioButton class:

● JRadioButton(): creates an unselected radio button with no text.


● JRadioButton(String s): creates an unselected radio button with specified text.
● JRadioButton(String s, boolean selected): creates a radio button with the specified text
and selected status.

Commonly used Methods of AbstractButton class:


1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this
object.

Note: The JRadioButton class extends the JToggleButton class that extends
AbstractButton class.

Example of JRadioButton class:

1. import javax.swing.*;
2. public class Radio {
3. JFrame f;
4.
5. Radio(){
6. f=new JFrame();
7.
8. JRadioButton r1=new JRadioButton("A) Male");
9. JRadioButton r2=new JRadioButton("B) FeMale");
10. r1.setBounds(50,100,70,30);
11. r2.setBounds(50,150,70,30);
12.
13. ButtonGroup bg=new ButtonGroup();
14. bg.add(r1);bg.add(r2);
15.
16. f.add(r1);f.add(r2);
17.
18. f.setSize(300,300);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new Radio();
24. }
25. }

ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only one button
can be selected.
JRadioButton example with event handling

1. import javax.swing.*;
2. import java.awt.event.*;
3. class RadioExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioExample(){
7.
8. rb1=new JRadioButton("Male");
9. rb1.setBounds(100,50,100,30);
10.
11. rb2=new JRadioButton("Female");
12. rb2.setBounds(100,100,100,30);
13.
14. ButtonGroup bg=new ButtonGroup();
15. bg.add(rb1);bg.add(rb2);
16.
17. b=new JButton("click");
18. b.setBounds(100,150,80,30);
19. b.addActionListener(this);
20.
21. add(rb1);add(rb2);add(b);
22.
23. setSize(300,300);
24. setLayout(null);
25. setVisible(true);
26. }
27. public void actionPerformed(ActionEvent e){
28. if(rb1.isSelected()){
29. JOptionPane.showMessageDialog(this,"You are male");
30. }
31. if(rb2.isSelected()){
32. JOptionPane.showMessageDialog(this,"You are female");
33. }
34. }
35. public static void main(String args[]){
36. new RadioExample();
37. }}
JTextArea
class (Swing Tutorial):
The JTextArea class is used to create a text area. It is a multiline area that displays the plain text
only.

Commonly used Constructors:

● JTextArea(): creates a text area that displays no text initially.


● JTextArea(String s): creates a text area that displays specified text initially.
● JTextArea(int row, int column): creates a text area with the specified number of rows
and columns that displays no text initially..
● JTextArea(String s, int row, int column): creates a text area with the specified number
of rows and columns that displays specified text.

Commonly used methods of JTextArea class:


1) public void setRows(int rows): is used to set specified number of rows.
2) public void setColumns(int cols):: is used to set specified number of columns.
3) public void setFont(Font f): is used to set the specified font.
4) public void insert(String s, int position): is used to insert the specified text on the specified
position.
5) public void append(String s): is used to append the given text to the end of the document.

Example of JTextField class:

1. import java.awt.Color;
2. import javax.swing.*;
3.
4. public class TArea {
5. JTextArea area;
6. JFrame f;
7. TArea(){
8. f=new JFrame();
9.
10. area=new JTextArea(300,300);
11. area.setBounds(10,30,300,300);
12.
13. area.setBackground(Color.black);
14. area.setForeground(Color.white);
15.
16. f.add(area);
17.
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new TArea();
24. }
25. }

JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time only one item
can be selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)

Commonly used methods of JComboBox class:


1) public void addItem(Object anObject): is used to add an item to the item list.
2) public void removeItem(Object anObject): is used to delete an item to the item list.
3) public void removeAllItems(): is used to remove all the items from the list.
4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.
5) public void addActionListener(ActionListener a): is used to add the ActionListener.
6) public void addItemListener(ItemListener i): is used to add the ItemListener.

Example of JComboBox class:

1. import javax.swing.*;
2. public class Combo {
3. JFrame f;
4. Combo(){
5. f=new JFrame("Combo ex");
6.
7. String country[]={"India","Aus","U.S.A","England","Newzeland"};
8.
9. JComboBox cb=new JComboBox(country);
10. cb.setBounds(50, 50,90,20);
11. f.add(cb);
12.
13. f.setLayout(null);
14. f.setSize(400,500);
15. f.setVisible(true);
16.
17. }
18. public static void main(String[] args) {
19. new Combo();
20.
21. }
22. }

JTable class (Swing Tutorial):


The JTable class is used to display the data on two dimensional tables of cells.
Commonly used Constructors of JTable class:

● JTable(): creates a table with empty cells.


● JTable(Object[][] rows, Object[] columns): creates a table with the specified data.

Example of JTable class:

1. import javax.swing.*;
2. public class MyTable {
3. JFrame f;
4. MyTable(){
5. f=new JFrame();
6.
7. String data[][]={ {"101","Amit","670000"},
8. {"102","Jai","780000"},
9. {"101","Sachin","700000"}};
10. String column[]={"ID","NAME","SALARY"};
11.
12. JTable jt=new JTable(data,column);
13. jt.setBounds(30,40,200,300);
14.
15. JScrollPane sp=new JScrollPane(jt);
16. f.add(sp);
17.
18. f.setSize(300,400);
19. // f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new MyTable();
24. }
25. }

JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user can select any
color.

Commonly used Constructors of JColorChooser class:


● JColorChooser(): is used to create a color chooser pane with white color initially.
● JColorChooser(Color initialColor): is used to create a color chooser pane with the
specified color initially.
Commonly used methods of JColorChooser class:
public static Color showDialog(Component c, String title, Color initialColor): is used to show
the color-chooser dialog box.

Example of JColorChooser class:

1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class JColorChooserExample extends JFrame implements ActionListener{
6. JButton b;
7. Container c;
8.
9. JColorChooserExample(){
10. c=getContentPane();
11. c.setLayout(new FlowLayout());
12.
13. b=new JButton("color");
14. b.addActionListener(this);
15.
16. c.add(b);
17. }
18.
19. public void actionPerformed(ActionEvent e) {
20. Color initialcolor=Color.RED;
21. Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
22. c.setBackground(color);
23. }
24.
25. public static void main(String[] args) {
26. JColorChooserExample ch=new JColorChooserExample();
27. ch.setSize(400,400);
28. ch.setVisible(true);
29. ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
30. }
31. }

JProgressBar class:
The JProgressBar class is used to display the progress of the task.

Commonly used Constructors of JProgressBar class:

● JProgressBar(): is used to create a horizontal progress bar but no string text.


● JProgressBar(int min, int max): is used to create a horizontal progress bar with the
specified minimum and maximum value.
● JProgressBar(int orient): is used to create a progress bar with the specified orientation,
it can be either Vertical or Horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
● JProgressBar(int orient, int min, int max): is used to create a progress bar with the
specified orientation, minimum and maximum value.

Commonly used methods of JProgressBar class:


1) public void setStringPainted(boolean b): is used to determine whether string should be
displayed.
2) public void setString(String s): is used to set value to the progress string.
3) public void setOrientation(int orientation): is used to set the orientation, it may be either
vertical or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL
constants..
4) public void setValue(int value): is used to set the current value on the progress bar.

Example of JProgressBar class:

1. import javax.swing.*;
2. public class MyProgress extends JFrame{
3. JProgressBar jb;
4. int i=0,num=0;
5.
6. MyProgress(){
7. jb=new JProgressBar(0,2000);
8. jb.setBounds(40,40,200,30);
9.
10. jb.setValue(0);
11. jb.setStringPainted(true);
12.
13. add(jb);
14. setSize(400,400);
15. setLayout(null);
16. }
17.
18. public void iterate(){
19. while(i<=2000){
20. jb.setValue(i);
21. i=i+20;
22. try{Thread.sleep(150);}catch(Exception e){}
23. }
24. }
25. public static void main(String[] args) {
26. MyProgress m=new MyProgress();
27. m.setVisible(true);
28. m.iterate();
29. }
30. }

JSlider class:
The JSlider is used to create the slider. By using JSlider a user can select a value from a specific
range.

Commonly used Constructors of JSlider class:

● JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
● JSlider(int orientation): creates a slider with the specified orientation set by either
JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.
● JSlider(int min, int max): creates a horizontal slider using the given min and max.
● JSlider(int min, int max, int value): creates a horizontal slider using the given min, max
and value.
● JSlider(int orientation, int min, int max, int value): creates a slider using the given
orientation, min, max and value.

Commonly used Methods of JSlider class:


1) public void setMinorTickSpacing(int n): is used to set the minor tick spacing to the slider.
2) public void setMajorTickSpacing(int n): is used to set the major tick spacing to the slider.
3) public void setPaintTicks(boolean b): is used to determine whether tick marks are painted.
4) public void setPaintLabels(boolean b): is used to determine whether labels are painted.
5) public void setPaintTracks(boolean b): is used to determine whether track is painted.

Simple example of JSlider class:

1. import javax.swing.*;
2.
3. public class SliderExample1 extends JFrame{
4.
5. public SliderExample1() {
6. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
7. JPanel panel=new JPanel();
8. panel.add(slider);
9.
10. add(panel);
11. }
12.
13. public static void main(String s[]) {
14. SliderExample1 frame=new SliderExample1();
15. frame.pack();
16. frame.setVisible(true);
17. }
18. }
Example of JSlider class that paints ticks:

1. import javax.swing.*;
2.
3. public class SliderExample extends JFrame{
4.
5. public SliderExample() {
6.
7. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
8. slider.setMinorTickSpacing(2);
9. slider.setMajorTickSpacing(10);
10.
11. slider.setPaintTicks(true);
12. slider.setPaintLabels(true);
13.
14. JPanel panel=new JPanel();
15. panel.add(slider);
16. add(panel);
17. }
18.
19. public static void main(String s[]) {
20. SliderExample frame=new SliderExample();
21. frame.pack();
22. frame.setVisible(true);
23.
24. }
25. }
Example of digital clock in swing:

1. import javax.swing.*;
2. import java.awt.*;
3. import java.text.*;
4. import java.util.*;
5. public class DigitalWatch implements Runnable{
6. JFrame f;
7. Thread t=null;
8. int hours=0, minutes=0, seconds=0;
9. String timeString = "";
10. JButton b;
11.
12. DigitalWatch(){
13. f=new JFrame();
14.
15. t = new Thread(this);
16. t.start();
17.
18. b=new JButton();
19. b.setBounds(100,100,100,50);
20.
21. f.add(b);
22. f.setSize(300,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26.
27. public void run() {
28. try {
29. while (true) {
30.
31. Calendar cal = Calendar.getInstance();
32. hours = cal.get( Calendar.HOUR_OF_DAY );
33. if ( hours > 12 ) hours -= 12;
34. minutes = cal.get( Calendar.MINUTE );
35. seconds = cal.get( Calendar.SECOND );
36.
37. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
38. Date date = cal.getTime();
39. timeString = formatter.format( date );
40.
41. printTime();
42.
43. t.sleep( 1000 ); // interval given in milliseconds
44. }
45. }
46. catch (Exception e) { }
47. }
48.
49. public void printTime(){
50. b.setText(timeString);
51. }
52.
53. public static void main(String[] args) {
54. new DigitalWatch();
55.
56.
57. }
58. }

Displaying graphics in swing:


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle):
is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
Example of displaying graphics in swing:

1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class DisplayGraphics extends Canvas{
5.
6. public void paint(Graphics g) {
7. g.drawString("Hello",40,40);
8. setBackground(Color.WHITE);
9. g.fillRect(130, 30,100, 80);
10. g.drawOval(30,130,50, 60);
11. setForeground(Color.RED);
12. g.fillOval(130,130,50, 60);
13. g.drawArc(30, 200, 40,50,90,60);
14. g.fillArc(30, 130, 40,50,180,40);
15.
16. }
17. public static void main(String[] args) {
18. DisplayGraphics m=new DisplayGraphics();
19. JFrame f=new JFrame();
20. f.add(m);
21. f.setSize(400,400);
22. //f.setLayout(null);
23. f.setVisible(true);
24. }
25.
26. }

Displaying image in swing:


For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.

Example of displaying image in swing:

1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }

Example of creating Edit menu for Notepad:


1. import javax.swing.*;
2. import java.awt.event.*;
3.
4. public class Notepad implements ActionListener{
5. JFrame f;
6. JMenuBar mb;
7. JMenu file,edit,help;
8. JMenuItem cut,copy,paste,selectAll;
9. JTextArea ta;
10.
11. Notepad(){
12. f=new JFrame();
13.
14. cut=new JMenuItem("cut");
15. copy=new JMenuItem("copy");
16. paste=new JMenuItem("paste");
17. selectAll=new JMenuItem("selectAll");
18.
19. cut.addActionListener(this);
20. copy.addActionListener(this);
21. paste.addActionListener(this);
22. selectAll.addActionListener(this);
23.
24. mb=new JMenuBar();
25. mb.setBounds(5,5,400,40);
26.
27. file=new JMenu("File");
28. edit=new JMenu("Edit");
29. help=new JMenu("Help");
30.
31. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
32.
33.
34. mb.add(file);mb.add(edit);mb.add(help);
35.
36. ta=new JTextArea();
37. ta.setBounds(5,30,460,460);
38.
39. f.add(mb);f.add(ta);
40.
41. f.setLayout(null);
42. f.setSize(500,500);
43. f.setVisible(true);
44. }
45.
46. public void actionPerformed(ActionEvent e) {
47. if(e.getSource()==cut)
48. ta.cut();
49. if(e.getSource()==paste)
50. ta.paste();
51. if(e.getSource()==copy)
52. ta.copy();
53. if(e.getSource()==selectAll)
54. ta.selectAll();
55. }
56.
57. public static void main(String[] args) {
58. new Notepad();
59. }
60. }

Example of open dialog box:


1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import java.io.*;
5.
6. public class OpenMenu extends JFrame implements ActionListener{
7. JMenuBar mb;
8. JMenu file;
9. JMenuItem open;
10. JTextArea ta;
11. OpenMenu(){
12. open=new JMenuItem("Open File");
13. open.addActionListener(this);
14.
15. file=new JMenu("File");
16. file.add(open);
17.
18. mb=new JMenuBar();
19. mb.setBounds(0,0,800,20);
20. mb.add(file);
21.
22. ta=new JTextArea(800,800);
23. ta.setBounds(0,20,800,800);
24.
25. add(mb);
26. add(ta);
27.
28. }
29. public void actionPerformed(ActionEvent e) {
30. if(e.getSource()==open){
31. openFile();
32. }
33. }
34.
35. void openFile(){
36. JFileChooser fc=new JFileChooser();
37. int i=fc.showOpenDialog(this);
38.
39. if(i==JFileChooser.APPROVE_OPTION){
40. File f=fc.getSelectedFile();
41. String filepath=f.getPath();
42.
43. displayContent(filepath);
44.
45. }
46.
47. }
48.
49. void displayContent(String fpath){
50. try{
51. BufferedReader br=new BufferedReader(new FileReader(fpath));
52. String s1="",s2="";
53.
54. while((s1=br.readLine())!=null){
55. s2+=s1+"\n";
56. }
57. ta.setText(s2);
58. br.close();
59. }catch (Exception e) {e.printStackTrace(); }
60. }
61.
62. public static void main(String[] args) {
63. OpenMenu om=new OpenMenu();
64. om.setSize(800,800);
65. om.setLayout(null);
66. om.setVisible(true);
67. om.setDefaultCloseOperation(EXIT_ON_CLOSE);
68. }
69. }

Notepad in Java with source code


Notepad in Java with source code: We can develop Notepad in java with the help of
AWT/Swing with event handling. Let's see the code of creating Notepad in java.

1. import java.io.*;
2. import java.util.Date;
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.*;
6. import javax.swing.event.*;
7.
8. /************************************/
9. class FileOperation
10. {
11. Notepad npd;
12.
13. boolean saved;
14. boolean newFileFlag;
15. String fileName;
16. String applicationTitle="Notepad - Java";
17.
18. File fileRef;
19. JFileChooser chooser;
20. /////////////////////////////
21. boolean isSave(){return saved;}
22. void setSave(boolean saved){this.saved=saved;}
23. String getFileName(){return new String(fileName);}
24. void setFileName(String fileName){this.fileName=new String(fileName);}
25. /////////////////////////
26. FileOperation(Notepad npd)
27. {
28. this.npd=npd;
29.
30. saved=true;
31. newFileFlag=true;
32. fileName=new String("Untitled");
33. fileRef=new File(fileName);
34. this.npd.f.setTitle(fileName+" - "+applicationTitle);
35.
36. chooser=new JFileChooser();
37. chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
38. chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
39. chooser.setCurrentDirectory(new File("."));
40.
41. }
42. //////////////////////////////////////
43.
44. boolean saveFile(File temp)
45. {
46. FileWriter fout=null;
47. try
48. {
49. fout=new FileWriter(temp);
50. fout.write(npd.ta.getText());
51. }
52. catch(IOException ioe){updateStatus(temp,false);return false;}
53. finally
54. {try{fout.close();}catch(IOException excp){}}
55. updateStatus(temp,true);
56. return true;
57. }
58. ////////////////////////
59. boolean saveThisFile()
60. {
61.
62. if(!newFileFlag)
63. {return saveFile(fileRef);}
64.
65. return saveAsFile();
66. }
67. ////////////////////////////////////
68. boolean saveAsFile()
69. {
70. File temp=null;
71. chooser.setDialogTitle("Save As...");
72. chooser.setApproveButtonText("Save Now");
73. chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
74. chooser.setApproveButtonToolTipText("Click me to save!");
75.
76. do
77. {
78. if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
79. return false;
80. temp=chooser.getSelectedFile();
81. if(!temp.exists()) break;
82. if( JOptionPane.showConfirmDialog(
83. this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to replace it?<h
tml>",
84. "Save As",JOptionPane.YES_NO_OPTION
85. )==JOptionPane.YES_OPTION)
86. break;
87. }while(true);
88.
89.
90. return saveFile(temp);
91. }
92.
93. ////////////////////////
94. boolean openFile(File temp)
95. {
96. FileInputStream fin=null;
97. BufferedReader din=null;
98.
99. try
100. {
101. fin=new FileInputStream(temp);
102. din=new BufferedReader(new InputStreamReader(fin));
103. String str=" ";
104. while(str!=null)
105. {
106. str=din.readLine();
107. if(str==null)
108. break;
109. this.npd.ta.append(str+"\n");
110. }
111.
112. }
113. catch(IOException ioe){updateStatus(temp,false);return false;}
114. finally
115. {try{din.close();fin.close();}catch(IOException excp){}}
116. updateStatus(temp,true);
117. this.npd.ta.setCaretPosition(0);
118. return true;
119. }
120. ///////////////////////
121. void openFile()
122. {
123. if(!confirmSave()) return;
124. chooser.setDialogTitle("Open File...");
125. chooser.setApproveButtonText("Open this");
126. chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
127. chooser.setApproveButtonToolTipText("Click me to open the selected file.!");
128.
129. File temp=null;
130. do
131. {
132. if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
133. return;
134. temp=chooser.getSelectedFile();
135.
136. if(temp.exists()) break;
137.
138. JOptionPane.showMessageDialog(this.npd.f,
139. "<html>"+temp.getName()+"<br>file not found.<br>"+
140. "Please verify the correct file name was given.<html>",
141. "Open", JOptionPane.INFORMATION_MESSAGE);
142.
143. } while(true);
144.
145. this.npd.ta.setText("");
146.
147. if(!openFile(temp))
148. {
149. fileName="Untitled"; saved=true;
150. this.npd.f.setTitle(fileName+" - "+applicationTitle);
151. }
152. if(!temp.canWrite())
153. newFileFlag=true;
154.
155. }
156. ////////////////////////
157. void updateStatus(File temp,boolean saved)
158. {
159. if(saved)
160. {
161. this.saved=true;
162. fileName=new String(temp.getName());
163. if(!temp.canWrite())
164. {fileName+="(Read only)"; newFileFlag=true;}
165. fileRef=temp;
166. npd.f.setTitle(fileName + " - "+applicationTitle);
167. npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
168. newFileFlag=false;
169. }
170. else
171. {
172. npd.statusBar.setText("Failed to save/open : "+temp.getPath());
173. }
174. }
175. ///////////////////////
176. boolean confirmSave()
177. {
178. String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"+

179. "Do you want to save the changes?<html>";


180. if(!saved)
181. {
182. int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
183. JOptionPane.YES_NO_CANCEL_OPTION);
184.
185. if(x==JOptionPane.CANCEL_OPTION) return false;
186. if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
187. }
188. return true;
189. }
190. ///////////////////////////////////////
191. void newFile()
192. {
193. if(!confirmSave()) return;
194.
195. this.npd.ta.setText("");
196. fileName=new String("Untitled");
197. fileRef=new File(fileName);
198. saved=true;
199. newFileFlag=true;
200. this.npd.f.setTitle(fileName+" - "+applicationTitle);
201. }
202. //////////////////////////////////////
203. }// end defination of class FileOperation
204. /************************************/
205. public class Notepad implements ActionListener, MenuConstants
206. {
207.
208. JFrame f;
209. JTextArea ta;
210. JLabel statusBar;
211.
212. private String fileName="Untitled";
213. private boolean saved=true;
214. String applicationName="Javapad";
215.
216. String searchString, replaceString;
217. int lastSearchIndex;
218.
219. FileOperation fileHandler;
220. FontChooser fontDialog=null;
221. FindDialog findReplaceDialog=null;
222. JColorChooser bcolorChooser=null;
223. JColorChooser fcolorChooser=null;
224. JDialog backgroundDialog=null;
225. JDialog foregroundDialog=null;
226. JMenuItem cutItem,copyItem, deleteItem, findItem, findNextItem,
227. replaceItem, gotoItem, selectAllItem;
228. /****************************/
229. Notepad()
230. {
231. f=new JFrame(fileName+" - "+applicationName);
232. ta=new JTextArea(30,60);
233. statusBar=new JLabel("|| Ln 1, Col 1 ",JLabel.RIGHT);
234. f.add(new JScrollPane(ta),BorderLayout.CENTER);
235. f.add(statusBar,BorderLayout.SOUTH);
236. f.add(new JLabel(" "),BorderLayout.EAST);
237. f.add(new JLabel(" "),BorderLayout.WEST);
238. createMenuBar(f);
239. //f.setSize(350,350);
240. f.pack();
241. f.setLocation(100,50);
242. f.setVisible(true);
243. f.setLocation(150,50);
244. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
245.
246. fileHandler=new FileOperation(this);
247.
248. /////////////////////
249.
250. ta.addCaretListener(
251. new CaretListener()
252. {
253. public void caretUpdate(CaretEvent e)
254. {
255. int lineNumber=0, column=0, pos=0;
256.
257. try
258. {
259. pos=ta.getCaretPosition();
260. lineNumber=ta.getLineOfOffset(pos);
261. column=pos-ta.getLineStartOffset(lineNumber);
262. }catch(Exception excp){}
263. if(ta.getText().length()==0){lineNumber=0; column=0;}
264. statusBar.setText("|| Ln "+(lineNumber+1)+", Col "+(column+1));
265. }
266. });
267. //////////////////
268. DocumentListener myListener = new DocumentListener()
269. {
270. public void changedUpdate(DocumentEvent e){fileHandler.saved=false;}
271. public void removeUpdate(DocumentEvent e){fileHandler.saved=false;}
272. public void insertUpdate(DocumentEvent e){fileHandler.saved=false;}
273. };
274. ta.getDocument().addDocumentListener(myListener);
275. /////////
276. WindowListener frameClose=new WindowAdapter()
277. {
278. public void windowClosing(WindowEvent we)
279. {
280. if(fileHandler.confirmSave())System.exit(0);
281. }
282. };
283. f.addWindowListener(frameClose);
284. //////////////////
285. /*
286. ta.append("Hello dear hello hi");
287. ta.append("\nwho are u dear mister hello");
288. ta.append("\nhello bye hel");
289. ta.append("\nHello");
290. ta.append("\nMiss u mister hello hell");
291. fileHandler.saved=true;
292. */
293. }
294. ////////////////////////////////////
295. void goTo()
296. {
297. int lineNumber=0;
298. try
299. {
300. lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
301. String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNu
mber);
302. if(tempStr==null)
303. {return;}
304. lineNumber=Integer.parseInt(tempStr);
305. ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
306. }catch(Exception e){}
307. }
308. ///////////////////////////////////
309. public void actionPerformed(ActionEvent ev)
310. {
311. String cmdText=ev.getActionCommand();
312. ////////////////////////////////////
313. if(cmdText.equals(fileNew))
314. fileHandler.newFile();
315. else if(cmdText.equals(fileOpen))
316. fileHandler.openFile();
317. ////////////////////////////////////
318. else if(cmdText.equals(fileSave))
319. fileHandler.saveThisFile();
320. ////////////////////////////////////
321. else if(cmdText.equals(fileSaveAs))
322. fileHandler.saveAsFile();
323. ////////////////////////////////////
324. else if(cmdText.equals(fileExit))
325. {if(fileHandler.confirmSave())System.exit(0);}
326. ////////////////////////////////////
327. else if(cmdText.equals(filePrint))
328. JOptionPane.showMessageDialog(
329. Notepad.this.f,
330. "Get ur printer repaired first! It seems u dont have one!",
331. "Bad Printer",
332. JOptionPane.INFORMATION_MESSAGE
333. );
334. ////////////////////////////////////
335. else if(cmdText.equals(editCut))
336. ta.cut();
337. ////////////////////////////////////
338. else if(cmdText.equals(editCopy))
339. ta.copy();
340. ////////////////////////////////////
341. else if(cmdText.equals(editPaste))
342. ta.paste();
343. ////////////////////////////////////
344. else if(cmdText.equals(editDelete))
345. ta.replaceSelection("");
346. ////////////////////////////////////
347. else if(cmdText.equals(editFind))
348. {
349. if(Notepad.this.ta.getText().length()==0)
350. return; // text box have no text
351. if(findReplaceDialog==null)
352. findReplaceDialog=new FindDialog(Notepad.this.ta);
353. findReplaceDialog.showDialog(Notepad.this.f,true);//find
354. }
355. ////////////////////////////////////
356. else if(cmdText.equals(editFindNext))
357. {
358. if(Notepad.this.ta.getText().length()==0)
359. return; // text box have no text
360.
361. if(findReplaceDialog==null)
362. statusBar.setText("Use Find option of Edit Menu first !!!!");
363. else
364. findReplaceDialog.findNextWithSelection();
365. }
366. ////////////////////////////////////
367. else if(cmdText.equals(editReplace))
368. {
369. if(Notepad.this.ta.getText().length()==0)
370. return; // text box have no text
371.
372. if(findReplaceDialog==null)
373. findReplaceDialog=new FindDialog(Notepad.this.ta);
374. findReplaceDialog.showDialog(Notepad.this.f,false);//replace
375. }
376. ////////////////////////////////////
377. else if(cmdText.equals(editGoTo))
378. {
379. if(Notepad.this.ta.getText().length()==0)
380. return; // text box have no text
381. goTo();
382. }
383. ////////////////////////////////////
384. else if(cmdText.equals(editSelectAll))
385. ta.selectAll();
386. ////////////////////////////////////
387. else if(cmdText.equals(editTimeDate))
388. ta.insert(new Date().toString(),ta.getSelectionStart());
389. ////////////////////////////////////
390. else if(cmdText.equals(formatWordWrap))
391. {
392. JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
393. ta.setLineWrap(temp.isSelected());
394. }
395. ////////////////////////////////////
396. else if(cmdText.equals(formatFont))
397. {
398. if(fontDialog==null)
399. fontDialog=new FontChooser(ta.getFont());
400.
401. if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
402. Notepad.this.ta.setFont(fontDialog.createFont());
403. }
404. ////////////////////////////////////
405. else if(cmdText.equals(formatForeground))
406. showForegroundColorDialog();
407. ////////////////////////////////////
408. else if(cmdText.equals(formatBackground))
409. showBackgroundColorDialog();
410. ////////////////////////////////////
411.
412. else if(cmdText.equals(viewStatusBar))
413. {
414. JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
415. statusBar.setVisible(temp.isSelected());
416. }
417. ////////////////////////////////////
418. else if(cmdText.equals(helpAboutNotepad))
419. {
420. JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",
421. JOptionPane.INFORMATION_MESSAGE);
422. }
423. else
424. statusBar.setText("This "+cmdText+" command is yet to be implemented");
425. }//action Performed
426. ////////////////////////////////////
427. void showBackgroundColorDialog()
428. {
429. if(bcolorChooser==null)
430. bcolorChooser=new JColorChooser();
431. if(backgroundDialog==null)
432. backgroundDialog=JColorChooser.createDialog
433. (Notepad.this.f,
434. formatBackground,
435. false,
436. bcolorChooser,
437. new ActionListener()
438. {public void actionPerformed(ActionEvent evvv){
439. Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
440. null);
441.
442. backgroundDialog.setVisible(true);
443. }
444. ////////////////////////////////////
445. void showForegroundColorDialog()
446. {
447. if(fcolorChooser==null)
448. fcolorChooser=new JColorChooser();
449. if(foregroundDialog==null)
450. foregroundDialog=JColorChooser.createDialog
451. (Notepad.this.f,
452. formatForeground,
453. false,
454. fcolorChooser,
455. new ActionListener()
456. {public void actionPerformed(ActionEvent evvv){
457. Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
458. null);
459.
460. foregroundDialog.setVisible(true);
461. }
462.
463. ///////////////////////////////////
464. JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)
465. {
466. JMenuItem temp=new JMenuItem(s,key);
467. temp.addActionListener(al);
468. toMenu.add(temp);
469.
470. return temp;
471. }
472. ////////////////////////////////////
473. JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionLis
tener al)
474. {
475. JMenuItem temp=new JMenuItem(s,key);
476. temp.addActionListener(al);
477. temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK));
478. toMenu.add(temp);
479.
480. return temp;
481. }
482. ////////////////////////////////////
483. JCheckBoxMenuItem createCheckBoxMenuItem(String s,
484. int key,JMenu toMenu,ActionListener al)
485. {
486. JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
487. temp.setMnemonic(key);
488. temp.addActionListener(al);
489. temp.setSelected(false);
490. toMenu.add(temp);
491.
492. return temp;
493. }
494. ////////////////////////////////////
495. JMenu createMenu(String s,int key,JMenuBar toMenuBar)
496. {
497. JMenu temp=new JMenu(s);
498. temp.setMnemonic(key);
499. toMenuBar.add(temp);
500. return temp;
501. }
502. /*********************************/
503. void createMenuBar(JFrame f)
504. {
505. JMenuBar mb=new JMenuBar();
506. JMenuItem temp;
507.
508. JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
509. JMenu editMenu=createMenu(editText,KeyEvent.VK_E,mb);
510. JMenu formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
511. JMenu viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
512. JMenu helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);
513.
514. createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
515. createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
516. createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
517. createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
518. fileMenu.addSeparator();
519. temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
520. temp.setEnabled(false);
521. createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);
522. fileMenu.addSeparator();
523. createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);
524.
525. temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);

526. temp.setEnabled(false);
527. editMenu.addSeparator();
528. cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this)
;
529. copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,t
his);
530. createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
531. deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
532. deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
533. editMenu.addSeparator();
534. findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,thi
s);
535. findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
536. findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
537. replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.V
K_H,this);
538. gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,t
his);
539. editMenu.addSeparator();
540. selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.
VK_A,this);
541. createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this)
542. .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));
543.
544. createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);

545.
546. createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
547. formatMenu.addSeparator();
548. createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
549. createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);
550.
551. createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSele
cted(true);
552. /************For Look and Feel***/
553. LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);
554.
555.
556. temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
557. temp.setEnabled(false);
558. helpMenu.addSeparator();
559. createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);
560.
561. MenuListener editMenuListener=new MenuListener()
562. {
563. public void menuSelected(MenuEvent evvvv)
564. {
565. if(Notepad.this.ta.getText().length()==0)
566. {
567. findItem.setEnabled(false);
568. findNextItem.setEnabled(false);
569. replaceItem.setEnabled(false);
570. selectAllItem.setEnabled(false);
571. gotoItem.setEnabled(false);
572. }
573. else
574. {
575. findItem.setEnabled(true);
576. findNextItem.setEnabled(true);
577. replaceItem.setEnabled(true);
578. selectAllItem.setEnabled(true);
579. gotoItem.setEnabled(true);
580. }
581. if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
582. {
583. cutItem.setEnabled(false);
584. copyItem.setEnabled(false);
585. deleteItem.setEnabled(false);
586. }
587. else
588. {
589. cutItem.setEnabled(true);
590. copyItem.setEnabled(true);
591. deleteItem.setEnabled(true);
592. }
593. }
594. public void menuDeselected(MenuEvent evvvv){}
595. public void menuCanceled(MenuEvent evvvv){}
596. };
597. editMenu.addMenuListener(editMenuListener);
598. f.setJMenuBar(mb);
599. }
600. /*************Constructor**************/
601. ////////////////////////////////////
602. public static void main(String[] s)
603. {
604. new Notepad();
605. }
606. }
607. /**************************************/
608. //public
609. interface MenuConstants
610. {
611. final String fileText="File";
612. final String editText="Edit";
613. final String formatText="Format";
614. final String viewText="View";
615. final String helpText="Help";
616.
617. final String fileNew="New";
618. final String fileOpen="Open...";
619. final String fileSave="Save";
620. final String fileSaveAs="Save As...";
621. final String filePageSetup="Page Setup...";
622. final String filePrint="Print";
623. final String fileExit="Exit";
624.
625. final String editUndo="Undo";
626. final String editCut="Cut";
627. final String editCopy="Copy";
628. final String editPaste="Paste";
629. final String editDelete="Delete";
630. final String editFind="Find...";
631. final String editFindNext="Find Next";
632. final String editReplace="Replace";
633. final String editGoTo="Go To...";
634. final String editSelectAll="Select All";
635. final String editTimeDate="Time/Date";
636.
637. final String formatWordWrap="Word Wrap";
638. final String formatFont="Font...";
639. final String formatForeground="Set Text color...";
640. final String formatBackground="Set Pad color...";
641.
642. final String viewStatusBar="Status Bar";
643.
644. final String helpHelpTopic="Help Topic";
645. final String helpAboutNotepad="About Javapad";
646.
647. final String aboutText="Your Javapad";
648. }

Calculator in Java with Source Code


Calculator in Java with Source Code: We can develop calculator in java with the help of
AWT/Swing with event handling. Let's see the code of creating calculator in java.

1. /*********************************************
2. Save this file as MyCalculator.java
3. to compile it use
4. javac MyCalculator.java
5. to use the calcuator do this
6. java MyCalculator
7.
8. **********************************************/
9. import java.awt.*;
10. import java.awt.event.*;
11. /*********************************************/
12.
13. public class MyCalculator extends Frame
14. {
15.
16. public boolean setClear=true;
17. double number, memValue;
18. char op;
19.
20. String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+/-", "." };
21. String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
22. String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
23. String specialButtonText[] = {"Backspc", "C", "CE" };
24.
25. MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];
26. MyOperatorButton operatorButton[]=new MyOperatorButton[operatorButtonText.leng
th];
27. MyMemoryButton memoryButton[]=new MyMemoryButton[memoryButtonText.length
];
28. MySpecialButton specialButton[]=new MySpecialButton[specialButtonText.length];
29.
30. Label displayLabel=new Label("0",Label.RIGHT);
31. Label memLabel=new Label(" ",Label.RIGHT);
32.
33. final int FRAME_WIDTH=325,FRAME_HEIGHT=325;
34. final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;
35. final int TOPX=30, TOPY=50;
36. ///////////////////////////
37. MyCalculator(String frameText)//constructor
38. {
39. super(frameText);
40.
41. int tempX=TOPX, y=TOPY;
42. displayLabel.setBounds(tempX,y,240,HEIGHT);
43. displayLabel.setBackground(Color.BLUE);
44. displayLabel.setForeground(Color.WHITE);
45. add(displayLabel);
46.
47. memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);
48. add(memLabel);
49.
50. // set Co-ordinates for Memory Buttons
51. tempX=TOPX;
52. y=TOPY+2*(HEIGHT+V_SPACE);
53. for(int i=0; i<memoryButton.length; i++)
54. {
55. memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[
i], this);
56. memoryButton[i].setForeground(Color.RED);
57. y+=HEIGHT+V_SPACE;
58. }
59.
60. //set Co-ordinates for Special Buttons
61. tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
62. for(int i=0;i<specialButton.length;i++)
63. {
64. specialButton[i]=new MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i],
this);
65. specialButton[i].setForeground(Color.RED);
66. tempX=tempX+2*WIDTH+H_SPACE;
67. }
68.
69. //set Co-ordinates for Digit Buttons
70. int digitX=TOPX+WIDTH+H_SPACE;
71. int digitY=TOPY+2*(HEIGHT+V_SPACE);
72. tempX=digitX; y=digitY;
73. for(int i=0;i<digitButton.length;i++)
74. {
75. digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i], this);
76. digitButton[i].setForeground(Color.BLUE);
77. tempX+=WIDTH+H_SPACE;
78. if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}
79. }
80.
81. //set Co-ordinates for Operator Buttons
82. int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;
83. int opsY=digitY;
84. tempX=opsX; y=opsY;
85. for(int i=0;i<operatorButton.length;i++)
86. {
87. tempX+=WIDTH+H_SPACE;
88. operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonTex
t[i], this);
89. operatorButton[i].setForeground(Color.RED);
90. if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
91. }
92.
93. addWindowListener(new WindowAdapter()
94. {
95. public void windowClosing(WindowEvent ev)
96. {System.exit(0);}
97. });
98.
99. setLayout(null);
100. setSize(FRAME_WIDTH,FRAME_HEIGHT);
101. setVisible(true);
102. }
103. //////////////////////////////////
104. static String getFormattedText(double temp)
105. {
106. String resText=""+temp;
107. if(resText.lastIndexOf(".0")>0)
108. resText=resText.substring(0,resText.length()-2);
109. return resText;
110. }
111. ////////////////////////////////////////
112. public static void main(String []args)
113. {
114. new MyCalculator("Calculator - Java");
115. }
116. }
117.
118. /*******************************************/
119.
120. class MyDigitButton extends Button implements ActionListener
121. {
122. MyCalculator cl;
123.
124. //////////////////////////////////////////
125. MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)
126. {
127. super(cap);
128. setBounds(x,y,width,height);
129. this.cl=clc;
130. this.cl.add(this);
131. addActionListener(this);
132. }
133. ////////////////////////////////////////////////
134. static boolean isInString(String s, char ch)
135. {
136. for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
137. return false;
138. }
139. /////////////////////////////////////////////////
140. public void actionPerformed(ActionEvent ev)
141. {
142. String tempText=((MyDigitButton)ev.getSource()).getLabel();
143.
144. if(tempText.equals("."))
145. {
146. if(cl.setClear)
147. {cl.displayLabel.setText("0.");cl.setClear=false;}
148. else if(!isInString(cl.displayLabel.getText(),'.'))
149. cl.displayLabel.setText(cl.displayLabel.getText()+".");
150. return;
151. }
152.
153. int index=0;
154. try{
155. index=Integer.parseInt(tempText);
156. }catch(NumberFormatException e){return;}
157.
158. if (index==0 && cl.displayLabel.getText().equals("0")) return;
159.
160. if(cl.setClear)
161. {cl.displayLabel.setText(""+index);cl.setClear=false;}
162. else
163. cl.displayLabel.setText(cl.displayLabel.getText()+index);
164. }//actionPerformed
165. }//class defination
166.
167. /********************************************/
168.
169. class MyOperatorButton extends Button implements ActionListener
170. {
171. MyCalculator cl;
172.
173. MyOperatorButton(int x,int y, int width,int height,String cap, MyCalculator clc)
174. {
175. super(cap);
176. setBounds(x,y,width,height);
177. this.cl=clc;
178. this.cl.add(this);
179. addActionListener(this);
180. }
181. ///////////////////////
182. public void actionPerformed(ActionEvent ev)
183. {
184. String opText=((MyOperatorButton)ev.getSource()).getLabel();
185.
186. cl.setClear=true;
187. double temp=Double.parseDouble(cl.displayLabel.getText());
188.
189. if(opText.equals("1/x"))
190. {
191. try
192. {double tempd=1/(double)temp;
193. cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
194. catch(ArithmeticException excp)
195. {cl.displayLabel.setText("Divide by 0.");}
196. return;
197. }
198. if(opText.equals("sqrt"))
199. {
200. try
201. {double tempd=Math.sqrt(temp);
202. cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
203. catch(ArithmeticException excp)
204. {cl.displayLabel.setText("Divide by 0.");}
205. return;
206. }
207. if(!opText.equals("="))
208. {
209. cl.number=temp;
210. cl.op=opText.charAt(0);
211. return;
212. }
213. // process = button pressed
214. switch(cl.op)
215. {
216. case '+':
217. temp+=cl.number;break;
218. case '-':
219. temp=cl.number-temp;break;
220. case '*':
221. temp*=cl.number;break;
222. case '%':
223. try{temp=cl.number%temp;}
224. catch(ArithmeticException excp)
225. {cl.displayLabel.setText("Divide by 0."); return;}
226. break;
227. case '/':
228. try{temp=cl.number/temp;}
229. catch(ArithmeticException excp)
230. {cl.displayLabel.setText("Divide by 0."); return;}
231. break;
232. }//switch
233.
234. cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
235. //cl.number=temp;
236. }//actionPerformed
237. }//class
238.
239. /****************************************/
240.
241. class MyMemoryButton extends Button implements ActionListener
242. {
243. MyCalculator cl;
244.
245. /////////////////////////////////
246. MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)
247. {
248. super(cap);
249. setBounds(x,y,width,height);
250. this.cl=clc;
251. this.cl.add(this);
252. addActionListener(this);
253. }
254. ////////////////////////////////////////////////
255. public void actionPerformed(ActionEvent ev)
256. {
257. char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
258.
259. cl.setClear=true;
260. double temp=Double.parseDouble(cl.displayLabel.getText());
261.
262. switch(memop)
263. {
264. case 'C':
265. cl.memLabel.setText(" ");cl.memValue=0.0;break;
266. case 'R':
267. cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break;
268. case 'S':
269. cl.memValue=0.0;
270. case '+':
271. cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
272. if(cl.displayLabel.getText().equals("0") || cl.displayLabel.getText().equals("0.0"
) )
273. cl.memLabel.setText(" ");
274. else
275. cl.memLabel.setText("M");
276. break;
277. }//switch
278. }//actionPerformed
279. }//class
280.
281. /*****************************************/
282.
283. class MySpecialButton extends Button implements ActionListener
284. {
285. MyCalculator cl;
286.
287. MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)
288. {
289. super(cap);
290. setBounds(x,y,width,height);
291. this.cl=clc;
292. this.cl.add(this);
293. addActionListener(this);
294. }
295. //////////////////////
296. static String backSpace(String s)
297. {
298. String Res="";
299. for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
300. return Res;
301. }
302.
303. //////////////////////////////////////////////////////////
304. public void actionPerformed(ActionEvent ev)
305. {
306. String opText=((MySpecialButton)ev.getSource()).getLabel();
307. //check for backspace button
308. if(opText.equals("Backspc"))
309. {
310. String tempText=backSpace(cl.displayLabel.getText());
311. if(tempText.equals(""))
312. cl.displayLabel.setText("0");
313. else
314. cl.displayLabel.setText(tempText);
315. return;
316. }
317. //check for "C" button i.e. Reset
318. if(opText.equals("C"))
319. {
320. cl.number=0.0; cl.op=' '; cl.memValue=0.0;
321. cl.memLabel.setText(" ");
322. }
323.
324. //it must be CE button pressed
325. cl.displayLabel.setText("0");cl.setClear=true;
326. }//actionPerformed
327. }//class
328.
329. /*********************************************
330. Features not implemented and few bugs
331.
332. i) No coding done for "+/-" button.
333. ii) Menubar is not included.
334. iii)Not for Scientific calculation
335. iv)Some of the computation may lead to unexpected result
336. due to the representation of Floating point numbers in computer
337. is an approximation to the given value that can be stored
338. physically in memory.
339. ***********************************************/

IP Finder in Java with Source Code


IP Finder in Java with Source Code: We can develop IP Finder in java with the help of
Networking, AWT/Swing with event handling. Let's see the code of creating IP Finder in java.

1. String url="www.java.com";
2. InetAddress ia=InetAddress.getByName(url);
3. String ip=ia.getHostAddress();

Let's see the Swing code to find IP address.

1. import javax.swing.*;
2. import java.awt.event.*;
3. import java.net.*;
4. public class IPFinder extends JFrame implements ActionListener{
5. JLabel l;
6. JTextField tf;
7. JButton b;
8. IPFinder(){
9. super("IP Finder Tool - Java");
10. l=new JLabel("Enter URL:");
11. l.setBounds(50,70,150,20);;
12. tf=new JTextField();
13. tf.setBounds(50,100,200,20);
14.
15. b=new JButton("Find IP");
16. b.setBounds(50,150,80,30);
17. b.addActionListener(this);
18. add(l);
19. add(tf);
20. add(b);
21. setSize(300,300);
22. setLayout(null);
23. setVisible(true);
24. }
25. public void actionPerformed(ActionEvent e){
26. String url=tf.getText();
27. try {
28. InetAddress ia=InetAddress.getByName(url);
29. String ip=ia.getHostAddress();
30. JOptionPane.showMessageDialog(this,ip);
31. } catch (UnknownHostException e1) {
32. JOptionPane.showMessageDialog(this,e1.toString());
33. }
34. }
35. public static void main(String[] args) {
36. new IPFinder();
37. }
38. }

Word Character Counter in Java with Source Code


Word Character Counter in Java with Source Code: We can develop Word Character
Counter in java with the help of string, AWT/Swing with event handling. Let's see the code of
creating Word Character Counter in java.

1. String text="hello java this is wcc tool";


2. String words[]=text.split("\\s");
3. int length=words.length;//returns total number of words
4. int clength=text.length();//returns total number of characters with space

Let's see the swing code to count word and character.

1. import java.awt.event.*;
2. import javax.swing.*;
3. public class WCC extends JFrame implements ActionListener{
4. JTextArea ta;
5. JButton b1,b2;
6. WCC(){
7. super("Word Character Counter - Java");
8. ta=new JTextArea();
9. ta.setBounds(50,50,300,200);
10.
11. b1=new JButton("Word");
12. b1.setBounds(50,300,100,30);
13.
14. b2=new JButton("Character");
15. b2.setBounds(180,300,100,30);
16.
17. b1.addActionListener(this);
18. b2.addActionListener(this);
19. add(b1);add(b2);add(ta);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. }
24. public void actionPerformed(ActionEvent e){
25. String text=ta.getText();
26. if(e.getSource()==b1){
27. String words[]=text.split("\\s");
28. JOptionPane.showMessageDialog(this,"Total words: "+words.length);
29. }
30. if(e.getSource()==b2){
31. JOptionPane.showMessageDialog(this,"Total Characters with space: "+text.length())
;
32. }
33. }
34. public static void main(String[] args) {
35. new WCC();
36. }
37. }

URL Source Code Generator in Java with Source Code


URL Source Code Generator in Java with Source Code: We can develop URL Source Code
Generator in java with the help of networking, AWT/Swing with event handling. Let's see the
code of creating URL Source Code Generator in java.

1. URL u=new URL("https://www.facebook.com");//change the URL


2. URLConnection uc=u.openConnection();
3. InputStream is=uc.getInputStream();
4. int i;
5. StringBuilder sb=new StringBuilder();
6. while((i=is.read())!=-1){
7. sb.append((char)i);
8. }
9. String source=sb.toString();

Let's see the swing code to generate Source Code of URL.

1. import java.awt.*;
2. import java.awt.event.*;
3. import java.io.InputStream;
4. import java.net.*;
5. public class SourceGetter extends Frame implements ActionListener{
6. TextField tf;
7. TextArea ta;
8. Button b;
9. Label l;
10. SourceGetter(){
11. super("Source Getter Tool - Java");
12. l=new Label("Enter URL:");
13. l.setBounds(50,50,50,20);
14.
15. tf=new TextField();
16. tf.setBounds(120,50,250,20);
17.
18. b=new Button("Get Source Code");
19. b.setBounds(120, 100,120,30);
20. b.addActionListener(this);
21.
22. ta=new TextArea();
23. ta.setBounds(120,150,250,150);
24.
25. add(l);add(tf);add(b);add(ta);
26. setSize(400,400);
27. setLayout(null);
28. setVisible(true);
29. }
30. public void actionPerformed(ActionEvent e){
31. String s=tf.getText();
32. if(s==null){}
33. else{
34. try{
35. URL u=new URL(s);
36. URLConnection uc=u.openConnection();
37.
38. InputStream is=uc.getInputStream();
39. int i;
40. StringBuilder sb=new StringBuilder();
41. while((i=is.read())!=-1){
42. sb.append((char)i);
43. }
44. String source=sb.toString();
45. ta.setText(source);
46. }catch(Exception ex){System.out.println(e);}
47. }
48. }
49. public static void main(String[] args) {
50. new SourceGetter();
51. }
52. }

Folder Explorer in Java with Source Code


Folder Explorer in Java with Source Code: We can develop Folder Explorer in java with the
help of IO Stream, AWT/Swing with event handling. Let's see the code of creating Folder
Explorer in java.

1. import java.io.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.*;
5. import javax.swing.tree.*;
6. /***********************************/
7. class Explorer extends JPanel implements ActionListener
8. {
9. JTextField jtf;
10. JTextArea jta;
11. JTree tree;
12. JButton refresh;
13. JTable jtb;
14. JScrollPane jsp;
15. JScrollPane jspTable;
16.
17. String currDirectory=null;
18.
19. final String[] colHeads={"File Name","SIZE(in Bytes)","Read Only","Hidden"};
20. String[][]data={{"","","","",""}};
21.
22. /////////////////////////////////
23. Explorer(String path)
24. {
25.
26. jtf=new JTextField();
27. jta=new JTextArea(5,30);
28. refresh=new JButton("Refresh");
29.
30. File temp=new File(path);
31. DefaultMutableTreeNode top=createTree(temp);
32.
33. //if(top!=null)
34.
35. tree=new JTree(top);
36.
37. jsp=new JScrollPane(tree);
38.
39. final String[] colHeads={"File Name","SIZE(in Bytes)","Read Only","Hidden"};
40. String[][]data={{"","","","",""}};
41. jtb=new JTable(data, colHeads);
42. jspTable=new JScrollPane(jtb);
43.
44. setLayout(new BorderLayout());
45. add(jtf,BorderLayout.NORTH);
46. add(jsp,BorderLayout.WEST);
47. add(jspTable,BorderLayout.CENTER);
48. add(refresh,BorderLayout.SOUTH);
49.
50. tree.addMouseListener(
51. new MouseAdapter()
52. {
53. public void mouseClicked(MouseEvent me)
54. {
55. doMouseClicked(me);
56. }
57. });
58. jtf.addActionListener(this);
59. refresh.addActionListener(this);
60. }
61. ///////////////////////////////
62. public void actionPerformed(ActionEvent ev)
63. {
64. File temp=new File(jtf.getText());
65. DefaultMutableTreeNode newtop=createTree(temp);
66. if(newtop!=null)
67. tree=new JTree(newtop);
68. remove(jsp);
69. jsp=new JScrollPane(tree);
70. setVisible(false);
71. add(jsp,BorderLayout.WEST);
72. tree.addMouseListener(
73. new MouseAdapter()
74. {
75. public void mouseClicked(MouseEvent me)
76. {
77. doMouseClicked(me);
78. }
79. });
80.
81. setVisible(true);
82. }
83. //////////////////////////////
84.
85. DefaultMutableTreeNode createTree(File temp)
86. {
87. DefaultMutableTreeNode top=new DefaultMutableTreeNode(temp.getPath());
88. if(!(temp.exists() && temp.isDirectory()))
89. return top;
90.
91. fillTree(top,temp.getPath());
92.
93. return top;
94. }
95. //////////////////////////////
96. void fillTree(DefaultMutableTreeNode root, String filename)
97. {
98. File temp=new File(filename);
99.
100. if(!(temp.exists() && temp.isDirectory()))
101. return;
102. //System.out.println(filename);
103. File[] filelist=temp.listFiles();
104.
105. for(int i=0; i<filelist.length; i++)
106. {
107. if(!filelist[i].isDirectory())
108. continue;
109. final DefaultMutableTreeNode tempDmtn=new DefaultMutableTreeNode(filelist
[i].getName());
110. root.add(tempDmtn);
111. final String newfilename=new String(filename+"\\"+filelist[i].getName());
112. Thread t=new Thread()
113. {
114. public void run()
115. {
116. fillTree(tempDmtn,newfilename);
117. }//run
118. };//thread
119. if(t==null)
120. {System.out.println("no more thread allowed "+newfilename);return;}
121. t.start();
122. }//for
123. }//function
124. //////////////////////////////
125. void doMouseClicked(MouseEvent me)
126. {
127. TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
128. if(tp==null) return;
129. //jtf.setText(tp.toString());
130. String s=tp.toString();
131. s=s.replace("[","");
132. s=s.replace("]","");
133. s=s.replace(", ","\\");
134. //s=s.replace(" ","");
135. //int z=s.lastIndexOf("\"\\\"");
136. //s="\'"+s; s=s+"\'";
137. jtf.setText(s);
138. showFiles(s);
139. //java.util.StringTokenizer st=new java.util.StringTokenizer(s,",");
140. //jtf.setText(jtf.getText()+"="+s);
141.
142. }
143. ////////////////////////////////
144. void showFiles(String filename)
145. {
146. File temp=new File(filename);
147. data=new String[][]{{"","","",""}};
148. remove(jspTable);
149. jtb=new JTable(data, colHeads);
150. jspTable=new JScrollPane(jtb);
151. setVisible(false);
152. add(jspTable,BorderLayout.CENTER);
153. setVisible(true);
154.
155. if(!temp.exists()) return;
156. if(!temp.isDirectory()) return;
157.
158. //System.out.println(filename);
159. File[] filelist=temp.listFiles();
160. int fileCounter=0;
161. data=new String[filelist.length][4];
162. for(int i=0; i<filelist.length; i++)
163. {
164. if(filelist[i].isDirectory())
165. continue;
166. data[fileCounter][0]=new String(filelist[i].getName());
167. data[fileCounter][1]=new String(filelist[i].length()+"");
168. data[fileCounter][2]=new String(!filelist[i].canWrite()+"");
169. data[fileCounter][3]=new String(filelist[i].isHidden()+"");
170. fileCounter++;
171. }//for
172.
173. String dataTemp[][]=new String[fileCounter][4];
174. for(int k=0; k<fileCounter; k++)
175. dataTemp[k]=data[k];
176. data=dataTemp;
177.
178. //System.out.println(data);
179. remove(jspTable);
180. jtb=new JTable(data, colHeads);
181. jspTable=new JScrollPane(jtb);
182. setVisible(false);
183. add(jspTable,BorderLayout.CENTER);
184. setVisible(true);
185. }
186. ////////////////////////////////
187. ///////////////////////////////
188. }
189. /***********************************/
190. class ExplorerTest extends JFrame
191. {
192.
193. ExplorerTest(String path)
194. {
195. super("Windows Exploder - Java");
196. add(new Explorer(path),"Center");
197. setDefaultCloseOperation(EXIT_ON_CLOSE);
198. setSize(400,400);
199. setVisible(true);
200. }
201.
202. public static void main(String[] args)
203. {
204. new ExplorerTest(".");
205. }
206. }
207. /***********************************/

Puzzle Game in Java


Puzzle Game in Java with Source Code: We can develop Puzzle Game in java with the help of
AWT/Swing with event handling. Let's see the code of creating Puzzle Game in java.

1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class puzzle extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,next;
6. puzzle(){
7. super("Puzzle Game - Java");
8. b1=new JButton("1");
9. b2=new JButton(" ");
10. b3=new JButton("3");
11. b4=new JButton("4");
12. b5=new JButton("5");
13. b6=new JButton("6");
14. b7=new JButton("7");
15. b8=new JButton("8");
16. b9=new JButton("2");
17. next=new JButton("next");
18.
19. b1.setBounds(10,30,50,40);
20. b2.setBounds(70,30,50,40);
21. b3.setBounds(130,30,50,40);
22. b4.setBounds(10,80,50,40);
23. b5.setBounds(70,80,50,40);
24. b6.setBounds(130,80,50,40);
25. b7.setBounds(10,130,50,40);
26. b8.setBounds(70,130,50,40);
27. b9.setBounds(130,130,50,40);
28. next.setBounds(70,200,100,40);
29.
30. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); add(next);
31. b1.addActionListener(this);
32. b2.addActionListener(this);
33. b3.addActionListener(this);
34. b4.addActionListener(this);
35. b5.addActionListener(this);
36. b6.addActionListener(this);
37. b7.addActionListener(this);
38. b8.addActionListener(this);
39. b9.addActionListener(this);
40. next.addActionListener(this);
41.
42. next.setBackground(Color.black);
43. next.setForeground(Color.green);
44. setSize(250,300);
45. setLayout(null);
46. setVisible(true);
47. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
48. }//end of constructor
49.
50. public void actionPerformed(ActionEvent e){
51. if(e.getSource()==next){
52. String s=b4.getLabel();
53. b4.setLabel(b9.getLabel());
54. b9.setLabel(s);
55. s=b1.getLabel();
56. b1.setLabel(b5.getLabel());
57. b5.setLabel(s);
58. s=b2.getLabel();
59. b2.setLabel(b7.getLabel());
60. b7.setLabel(s);
61. }
62. if(e.getSource()==b1){
63. String s=b1.getLabel();
64. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b1.setLabel(" ");}
65. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b1.setLabel(" ");}
66. }//end of if
67.
68. if(e.getSource()==b3){
69. String s=b3.getLabel();
70. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b3.setLabel(" ");}
71. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b3.setLabel(" ");}
72. }//end of if
73.
74. if(e.getSource()==b2){
75. String s=b2.getLabel();
76. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b2.setLabel(" ");}
77. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b2.setLabel(" ");}
78. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b2.setLabel(" ");}
79. }//end of if
80.
81. if(e.getSource()==b4){
82. String s=b4.getLabel();
83. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b4.setLabel(" ");}
84. else if(b7.getLabel().equals(" ")){ b7.setLabel(s); b4.setLabel(" ");}
85. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b4.setLabel(" ");}
86. }//end of if
87.
88. if(e.getSource()==b5){
89. String s=b5.getLabel();
90. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b5.setLabel(" ");}
91. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b5.setLabel(" ");}
92. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b5.setLabel(" ");}
93. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b5.setLabel(" ");}
94. }//end of if
95.
96. if(e.getSource()==b6){
97.
98. String s=b6.getLabel();
99. if(b9.getLabel().equals(" ")){ b9.setLabel(s); b6.setLabel(" ");}
100. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b6.setLabel(" ");}
101. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b6.setLabel(" ");}
102.
103. }//end of if
104.
105. if(e.getSource()==b7){
106. String s=b7.getLabel();
107. if(b4.getLabel().equals(" ")){ b4.setLabel(s); b7.setLabel(" ");}
108. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b7.setLabel(" ");}
109.
110. }//end of if
111.
112. if(e.getSource()==b8){
113. String s=b8.getLabel();
114. if(b7.getLabel().equals(" ")){ b7.setLabel(s); b8.setLabel(" ");}
115. else if(b9.getLabel().equals(" ")){ b9.setLabel(s); b8.setLabel(" ");}
116. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b8.setLabel(" ");}
117.
118. }//end of if
119.
120. if(e.getSource()==b9){
121. String s=b9.getLabel();
122. if(b6.getLabel().equals(" ")){ b6.setLabel(s); b9.setLabel(" ");}
123. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b9.setLabel(" ");}
124. if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")&&b3.getLabel()
125. .equals("3")&&b4.getLabel().equals("4")&&b5.getLabel().equals("5")
126. &&b6.getLabel().equals("6")&&b7.getLabel().equals("7")&&b8.getLabel()
127. .equals("8")&&b9.getLabel().equals(" ")){
128. JOptionPane.showMessageDialog(puzzle.this,"!!!you won!!!");
129. }
130. }//end of if
131.
132. }//end of actionPerformed
133.
134.
135. public static void main(String[] args){
136. new puzzle();
137. }//end of main
138.
139. }//end of class
Example of Pic Puzzle Game

1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4. class picpuzzle2 extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,sample,starB;
6. Icon star;
7. Icon ic0=new ImageIcon("pic/starB0.jpg");
8. Icon ic10=new ImageIcon("pic/starB10.jpg");
9. Icon ic20=new ImageIcon("pic/starB20.jpg");
10. Icon samicon1=new ImageIcon("pic/main.jpg");
11. Icon samicon2=new ImageIcon("pic/main2.jpg");
12. Icon samicon3=new ImageIcon("pic/main3.jpg");
13. Icon ic1=new ImageIcon("pic/1.jpg");
14. Icon ic2=new ImageIcon("pic/5.jpg");
15. Icon ic3=new ImageIcon("pic/2.jpg");
16. Icon ic4=new ImageIcon("pic/7.jpg");
17. Icon ic5=new ImageIcon("pic/4.jpg");
18. Icon ic6=new ImageIcon("pic/6.jpg");
19. Icon ic7=new ImageIcon("pic/8.jpg");
20. Icon ic8=new ImageIcon("pic/9.jpg");
21. Icon ic9=new ImageIcon("pic/3.jpg");
22.
23. Icon ic11=new ImageIcon("pic/12.jpg");
24. Icon ic12=new ImageIcon("pic/13.jpg");
25. Icon ic13=new ImageIcon("pic/16.jpg");
26. Icon ic14=new ImageIcon("pic/11.jpg");
27. Icon ic15=new ImageIcon("pic/14.jpg");
28. Icon ic16=new ImageIcon("pic/19.jpg");
29. Icon ic17=new ImageIcon("pic/17.jpg");
30. Icon ic18=new ImageIcon("pic/15.jpg");
31. Icon ic19=new ImageIcon("pic/18.jpg");
32.
33. Icon ic21=new ImageIcon("pic/24.jpg");
34. Icon ic22=new ImageIcon("pic/25.jpg");
35. Icon ic23=new ImageIcon("pic/21.jpg");
36. Icon ic24=new ImageIcon("pic/27.jpg");
37. Icon ic25=new ImageIcon("pic/23.jpg");
38. Icon ic26=new ImageIcon("pic/29.jpg");
39. Icon ic27=new ImageIcon("pic/28.jpg");
40. Icon ic28=new ImageIcon("pic/22.jpg");
41. Icon ic29=new ImageIcon("pic/26.jpg");
42.
43. picpuzzle2(){
44.
45. super("pic puzzle");
46.
47. b1=new JButton(ic1);
48. b1.setBounds(10,80,100,100);
49. b2=new JButton(ic2);
50. b2.setBounds(110,80,100,100);
51. b3=new JButton(ic3);
52. b3.setBounds(210,80,100,100);
53. b4=new JButton(ic4);
54. b4.setBounds(10,180,100,100);
55. b5=new JButton(ic5);
56. b5.setBounds(110,180,100,100);
57. b6=new JButton(ic6);
58. b6.setBounds(210,180,100,100);
59. b7=new JButton(ic7);
60. b7.setBounds(10,280,100,100);
61. b8=new JButton(ic8);
62. b8.setBounds(110,280,100,100);
63. b9=new JButton(ic9);
64. b9.setBounds(210,280,100,100);
65. sample=new JButton(samicon1);
66. sample.setBounds(380,100,200,200);
67.
68. JLabel l1=new JLabel("Sample:");
69. l1.setBounds(330,200,70,20);
70. JLabel l2=new JLabel("NOTE:
71. icon has power to swap with neighbour icon=");
72. l2.setBounds(5,15,500,20);
73. JLabel l3=new JLabel("click sample picture to next puzzle");
74. l3.setBounds(380,320,200,20);
75. l3.setForeground(Color.red);
76.
77. starB=new JButton(ic0);
78. starB.setBounds(330,5,50,50);
79. star=b9.getIcon();
80.
81. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);
82. add(b9);add(sample);add(l1);add(l2);add(starB);add(l3);
83. b1.addActionListener(this); b2.addActionListener(this);
84. b3.addActionListener(this); b4.addActionListener(this);
85. b5.addActionListener(this); b6.addActionListener(this);
86. b7.addActionListener(this); b8.addActionListener(this);
87. b9.addActionListener(this);
88.
89. sample.addActionListener(this);
90. setLayout(null);
91. setSize(600,500);
92. setVisible(true);
93. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
94. }
95.
96. public void actionPerformed(ActionEvent e){
97. if(e.getSource()==b1){
98. Icon s1=b1.getIcon();
99. if(b2.getIcon()==star){
100. b2.setIcon(s1);
101. b1.setIcon(star);
102. } else if(b4.getIcon()==star){
103. b4.setIcon(s1);
104. b1.setIcon(star);
105. }
106. }//end of if
107.
108. if(e.getSource()==b2){
109. Icon s1=b2.getIcon();
110. if(b1.getIcon()==star){
111. b1.setIcon(s1);
112. b2.setIcon(star);
113. } else if(b5.getIcon()==star){
114. b5.setIcon(s1);
115. b2.setIcon(star);
116. }
117. else if(b3.getIcon()==star){
118. b3.setIcon(s1);
119. b2.setIcon(star);
120. }
121. }//end of if
122.
123. if(e.getSource()==b3){
124. Icon s1=b3.getIcon();
125. if(b2.getIcon()==star){
126. b2.setIcon(s1);
127. b3.setIcon(star);
128. } else if(b6.getIcon()==star){
129. b6.setIcon(s1);
130. b3.setIcon(star);
131. }
132. }//end of if
133.
134. if(e.getSource()==b4){
135. Icon s1=b4.getIcon();
136. if(b1.getIcon()==star){
137. b1.setIcon(s1);
138. b4.setIcon(star);
139. } else if(b5.getIcon()==star){
140. b5.setIcon(s1);
141. b4.setIcon(star);
142. }
143. else if(b7.getIcon()==star){
144. b7.setIcon(s1);
145. b4.setIcon(star);
146. }
147. }//end of if
148.
149. if(e.getSource()==b5){
150. Icon s1=b5.getIcon();
151. if(b2.getIcon()==star){
152. b2.setIcon(s1);
153. b5.setIcon(star);
154. } else if(b4.getIcon()==star){
155. b4.setIcon(s1);
156. b5.setIcon(star);
157. }
158. else if(b6.getIcon()==star){
159. b6.setIcon(s1);
160. b5.setIcon(star);
161. }
162. else if(b8.getIcon()==star){
163. b8.setIcon(s1);
164. b5.setIcon(star);
165. }
166. }//end of if
167.
168. if(e.getSource()==b6){
169. Icon s1=b6.getIcon();
170. if(b3.getIcon()==star){
171. b3.setIcon(s1);
172. b6.setIcon(star);
173. } else if(b5.getIcon()==star){
174. b5.setIcon(s1);
175. b6.setIcon(star);
176. }
177. else if(b9.getIcon()==star){
178. b9.setIcon(s1);
179. b6.setIcon(star);
180. }
181. }//end of if
182.
183. if(e.getSource()==b7){
184. Icon s1=b7.getIcon();
185. if(b4.getIcon()==star){
186. b4.setIcon(s1);
187. b7.setIcon(star);
188. } else if(b8.getIcon()==star){
189. b8.setIcon(s1);
190. b7.setIcon(star);
191. }
192. }//end of if
193.
194. if(e.getSource()==b8){
195. Icon s1=b8.getIcon();
196. if(b7.getIcon()==star){
197. b7.setIcon(s1);
198. b8.setIcon(star);
199. } else if(b5.getIcon()==star){
200. b5.setIcon(s1);
201. b8.setIcon(star);
202. }
203. else if(b9.getIcon()==star){
204. b9.setIcon(s1);
205. b8.setIcon(star);
206. }
207.
208. }//end of if
209.
210. if(e.getSource()==b9){
211. Icon s1=b9.getIcon();
212. if(b8.getIcon()==star){
213. b8.setIcon(s1);
214. b9.setIcon(star);
215. } else if(b6.getIcon()==star){
216. b6.setIcon(s1);
217. b9.setIcon(star);
218. }
219. }//end of if
220.
221. if(e.getSource()==sample){
222. Icon s1=sample.getIcon();
223. if(s1==samicon3){
224. sample.setIcon(samicon1);
225. b1.setIcon(ic1);
226. b2.setIcon(ic2);
227. b3.setIcon(ic3);
228. b4.setIcon(ic4);
229. b5.setIcon(ic5);
230. b6.setIcon(ic6);
231. b7.setIcon(ic7);
232. b8.setIcon(ic8);
233. b9.setIcon(ic9);
234. star=b9.getIcon();
235. starB.setIcon(ic0);
236. }//eof if
237. else if(s1==samicon1){
238. sample.setIcon(samicon2);
239. b1.setIcon(ic11);
240. b2.setIcon(ic12);
241. b3.setIcon(ic13);
242. b4.setIcon(ic14);
243. b5.setIcon(ic15);
244. b6.setIcon(ic16);
245. b7.setIcon(ic17);
246. b8.setIcon(ic18);
247. b9.setIcon(ic19);
248. star=b6.getIcon();
249. starB.setIcon(ic10);
250. }//eof else
251. else{
252. sample.setIcon(samicon3);
253. b1.setIcon(ic21);
254. b2.setIcon(ic22);
255. b3.setIcon(ic23);
256. b4.setIcon(ic24);
257. b5.setIcon(ic25);
258. b6.setIcon(ic26);
259. b7.setIcon(ic27);
260. b8.setIcon(ic28);
261. b9.setIcon(ic29);
262. star=b6.getIcon();
263. starB.setIcon(ic20);
264. }//eof else
265.
266. }
267. }//end of actionPerformed
268.
269. public static void main(String args[]){
270. new picpuzzle2();
271. }//end of main
272. }//end of class

Example of Tic Tac Toe Game in Swing


In this example, we are going to see the example of tic tac toe game (also known as 0 and x
(cross)).
It can be developed only through AWT api, but we are using here swing framework.
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. class TTT1 extends JFrame implements ItemListener, ActionListener{
5. int i,j,ii,jj,x,y,yesnull;
6. int a[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
7. {10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},
8. {10,7,8,9,11} };
9. int a1[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
10. {10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},{10,7,8,9,11} };
11.
12. boolean state,type,set;
13.
14. Icon ic1,ic2,icon,ic11,ic22;
15. Checkbox c1,c2;
16. JLabel l1,l2;
17. JButton b[]=new JButton[9];
18. JButton reset;
19.
20. public void showButton(){
21.
22. x=10; y=10;j=0;
23. for(i=0;i<=8;i++,x+=100,j++){
24. b[i]=new JButton();
25. if(j==3)
26. {j=0; y+=100; x=10;}
27. b[i].setBounds(x,y,100,100);
28. add(b[i]);
29. b[i].addActionListener(this);
30. }//eof for
31.
32. reset=new JButton("RESET");
33. reset.setBounds(100,350,100,50);
34. add(reset);
35. reset.addActionListener(this);
36.
37. }//eof showButton
38.
39. /*********************************************************/
40. public void check(int num1){
41. for(ii=0;ii<=7;ii++){
42. for(jj=1;jj<=3;jj++){
43. if(a[ii][jj]==num1){ a[ii][4]=11; }
44.
45. }//eof for jj
46.
47. }//eof for ii
48. }//eof check
49. /**********************************************************/
50.
51. /*********************************************************/
52.
53. public void complogic(int num){
54.
55. for(i=0;i<=7;i++){
56. for(j=1;j<=3;j++){
57. if(a[i][j]==num){ a[i][0]=11; a[i][4]=10; }
58. }
59. }
60. for(i=0;i<=7;i++){ // for 1
61. set=true;
62. if(a[i][4]==10){ //if 1
63. int count=0;
64. for(j=1;j<=3;j++){ //for 2
65. if(b[(a[i][j]-1)].getIcon()!=null){ //if 2
66. count++;
67. } //eof if 2
68. else{ yesnull=a[i][j]; }
69. } //eof for 2
70. if(count==2){ //if 2
71. b[yesnull-1].setIcon(ic2);
72. this.check(yesnull); set=false;break;
73. } //eof if 2
74. } //eof if 1
75. else
76. if(a[i][0]==10){
77. for(j=1;j<=3;j++){ //for2
78. if(b[(a[i][j]-1)].getIcon()==null){ //if 1
79. b[(a[i][j]-1)].setIcon(ic2);
80. this.check(a[i][j]);
81. set=false;
82. break;
83. } //eof if1
84. } //eof for 2
85. if(set==false)
86. break;
87. }//eof elseif
88.
89. if(set==false)
90. break;
91. }//eof for 1
92.
93.
94. }//eof complogic
95.
96.
97. /*********************************************************/
98.
99. TTT1(){
100. super("tic tac toe by ashwani");
101.
102. CheckboxGroup cbg=new CheckboxGroup();
103. c1=new Checkbox("vs computer",cbg,false);
104. c2=new Checkbox("vs friend",cbg,false);
105. c1.setBounds(120,80,100,40);
106. c2.setBounds(120,150,100,40);
107. add(c1); add(c2);
108. c1.addItemListener(this);
109. c2.addItemListener(this);
110.
111.
112. state=true;type=true;set=true;
113. ic1=new ImageIcon("ic1.jpg");
114. ic2=new ImageIcon("ic2.jpg");
115. ic11=new ImageIcon("ic11.jpg");
116. ic22=new ImageIcon("ic22.jpg");
117.
118. setLayout(null);
119. setSize(330,450);
120. setVisible(true);
121. setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
122. }//eof constructor
123.
124. /*************************************************************/
125. public void itemStateChanged(ItemEvent e){
126. if(c1.getState())
127. {
128. type=false;
129. }
130.
131. else if(c2.getState())
132. { type=true;
133. }
134. remove(c1);remove(c2);
135. repaint(0,0,330,450);
136. showButton();
137. }//eof itemstate
138. /************************************************************/
139.
140. public void actionPerformed(ActionEvent e){
141. /********************************/
142. if(type==true)//logicfriend
143. {
144. if(e.getSource()==reset){
145. for(i=0;i<=8;i++){
146. b[i].setIcon(null);
147. }//eof for
148. }
149. else{
150. for(i=0;i<=8;i++){
151. if(e.getSource()==b[i]){
152.
153. if(b[i].getIcon()==null){
154. if(state==true){ icon=ic2;
155. state=false;} else{ icon=ic1; state=true; }
156. b[i].setIcon(icon);
157. }
158. }
159. }//eof for
160. }//eof else
161. }//eof logicfriend
162. else if(type==false){ // complogic
163. if(e.getSource()==reset){
164. for(i=0;i<=8;i++){
165. b[i].setIcon(null);
166. }//eof for
167. for(i=0;i<=7;i++)
168. for(j=0;j<=4;j++)
169. a[i][j]=a1[i][j]; //again initialsing array
170. }
171. else{ //complogic
172. for(i=0;i<=8;i++){
173. if(e.getSource()==b[i]){
174. if(b[i].getIcon()==null){
175. b[i].setIcon(ic1);
176. if(b[4].getIcon()==null){
177. b[4].setIcon(ic2);
178. this.check(5);
179. } else{
180. this.complogic(i);
181. }
182. }
183. }
184. }//eof for
185. }
186. }//eof complogic
187.
188. for(i=0;i<=7;i++){
189.
190. Icon icon1=b[(a[i][1]-1)].getIcon();
191. Icon icon2=b[(a[i][2]-1)].getIcon();
192. Icon icon3=b[(a[i][3]-1)].getIcon();
193. if((icon1==icon2)&&(icon2==icon3)&&(icon1!=null)){
194. if(icon1==ic1){
195. b[(a[i][1]-1)].setIcon(ic11);
196. b[(a[i][2]-1)].setIcon(ic11);
197. b[(a[i][3]-1)].setIcon(ic11);
198. JOptionPane.showMessageDialog(TTT1.this,"!!!YOU won!!! click reset");
199. break;
200. }
201. else if(icon1==ic2){
202. b[(a[i][1]-1)].setIcon(ic22);
203. b[(a[i][2]-1)].setIcon(ic22);
204. b[(a[i][3]-1)].setIcon(ic22);
205. JOptionPane.showMessageDialog(TTT1.this,"won! click reset");
206. break;
207. }
208. }
209. }
210.
211.
212. }//eof actionperformed
213. /************************************************************/
214.
215. public static void main(String []args){
216. new TTT1();
217. }//eof main
218. }//eof class
Online Exam Project in Java Swing without database
In this project, there are given 10 questions to play. User can bookmark any question for the
reconsideration while going to result.
We are using here java array to store the questions, options and answers not database. You can
use collection framework or database in place of array.

1. /*Online Java Paper Test*/


2.
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.*;
6.
7. class OnlineTest extends JFrame implements ActionListener
8. {
9. JLabel l;
10. JRadioButton jb[]=new JRadioButton[5];
11. JButton b1,b2;
12. ButtonGroup bg;
13. int count=0,current=0,x=1,y=1,now=0;
14. int m[]=new int[10];
15. OnlineTest(String s)
16. {
17. super(s);
18. l=new JLabel();
19. add(l);
20. bg=new ButtonGroup();
21. for(int i=0;i<5;i++)
22. {
23. jb[i]=new JRadioButton();
24. add(jb[i]);
25. bg.add(jb[i]);
26. }
27. b1=new JButton("Next");
28. b2=new JButton("Bookmark");
29. b1.addActionListener(this);
30. b2.addActionListener(this);
31. add(b1);add(b2);
32. set();
33. l.setBounds(30,40,450,20);
34. jb[0].setBounds(50,80,100,20);
35. jb[1].setBounds(50,110,100,20);
36. jb[2].setBounds(50,140,100,20);
37. jb[3].setBounds(50,170,100,20);
38. b1.setBounds(100,240,100,30);
39. b2.setBounds(270,240,100,30);
40. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
41. setLayout(null);
42. setLocation(250,100);
43. setVisible(true);
44. setSize(600,350);
45. }
46. public void actionPerformed(ActionEvent e)
47. {
48. if(e.getSource()==b1)
49. {
50. if(check())
51. count=count+1;
52. current++;
53. set();
54. if(current==9)
55. {
56. b1.setEnabled(false);
57. b2.setText("Result");
58. }
59. }
60. if(e.getActionCommand().equals("Bookmark"))
61. {
62. JButton bk=new JButton("Bookmark"+x);
63. bk.setBounds(480,20+30*x,100,30);
64. add(bk);
65. bk.addActionListener(this);
66. m[x]=current;
67. x++;
68. current++;
69. set();
70. if(current==9)
71. b2.setText("Result");
72. setVisible(false);
73. setVisible(true);
74. }
75. for(int i=0,y=1;i<x;i++,y++)
76. {
77. if(e.getActionCommand().equals("Bookmark"+y))
78. {
79. if(check())
80. count=count+1;
81. now=current;
82. current=m[y];
83. set();
84. ((JButton)e.getSource()).setEnabled(false);
85. current=now;
86. }
87. }
88.
89. if(e.getActionCommand().equals("Result"))
90. {
91. if(check())
92. count=count+1;
93. current++;
94. //System.out.println("correct ans="+count);
95. JOptionPane.showMessageDialog(this,"correct ans="+count);
96. System.exit(0);
97. }
98. }
99. void set()
100. {
101. jb[4].setSelected(true);
102. if(current==0)
103. {
104. l.setText("Que1: Which one among these is not a primitive datatype?");
105. jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].set
Text("char");
106. }
107. if(current==1)
108. {
109. l.setText("Que2: Which class is available to all the class automatically?");
110. jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");jb[3].
setText("ActionEvent");
111. }
112. if(current==2)
113. {
114. l.setText("Que3: Which package is directly available to our class without i
mporting it?");
115. jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net");jb[3].set
Text("lang");
116. }
117. if(current==3)
118. {
119. l.setText("Que4: String class is defined in which package?");
120. jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3].se
tText("awt");
121. }
122. if(current==4)
123. {
124. l.setText("Que5: Which institute is best for java coaching?");
125. jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[3].s
etText("jtek");
126. }
127. if(current==5)
128. {
129. l.setText("Que6: Which one among these is not a keyword?");
130. jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setText(
"if");
131. }
132. if(current==6)
133. {
134. l.setText("Que7: Which one among these is not a class? ");
135. jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("Act
ionEvent");
136. jb[3].setText("Button");
137. }
138. if(current==7)
139. {
140. l.setText("Que8: which one among these is not a function of Object class?
");
141. jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals");
142. jb[3].setText("getDocumentBase");
143. }
144. if(current==8)
145. {
146. l.setText("Que9: which function is not present in Applet class?");
147. jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].setTe
xt("destroy");
148. }
149. if(current==9)
150. {
151. l.setText("Que10: Which one among these is not a valid component?");
152. jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGroup"
);
153. jb[3].setText("JTextArea");
154. }
155. l.setBounds(30,40,450,20);
156. for(int i=0,j=0;i<=90;i+=30,j++)
157. jb[j].setBounds(50,80+i,200,20);
158. }
159. boolean check()
160. {
161. if(current==0)
162. return(jb[1].isSelected());
163. if(current==1)
164. return(jb[2].isSelected());
165. if(current==2)
166. return(jb[3].isSelected());
167. if(current==3)
168. return(jb[0].isSelected());
169. if(current==4)
170. return(jb[2].isSelected());
171. if(current==5)
172. return(jb[2].isSelected());
173. if(current==6)
174. return(jb[1].isSelected());
175. if(current==7)
176. return(jb[3].isSelected());
177. if(current==8)
178. return(jb[1].isSelected());
179. if(current==9)
180. return(jb[2].isSelected());
181. return false;
182. }
183. public static void main(String s[])
184. {
185. new OnlineTest("Online Test Of Java");
186. }
187. }
Output

BorderLayout (LayoutManagers):
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

● BorderLayout(): creates a border layout but with no gaps between the components.
● JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }

GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout class:


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.

Fields of FlowLayout class:


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class:


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.

Example of FlowLayout class:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }

BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class:


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class:


1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.
Example of BoxLayout class with Y-AXIS:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample1 b=new BoxLayoutExample1();
22. }
23. }

Example of BoxLayout class with X-AXIS:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample2 b=new BoxLayoutExample2();
22. }
23. }

CardLayout class
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class:


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly used methods of CardLayout class:


● public void next(Container parent): is used to flip to the next card of the given
container.
● public void previous(Container parent): is used to flip to the previous card of the given
container.
● public void first(Container parent): is used to flip to the first card of the given container.
● public void last(Container parent): is used to flip to the last card of the given container.
● public void show(Container parent, String name): is used to flip to the specified card
with the given name.
Example of CardLayout class:

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37. }

Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

● It works at client side so less response time.


● Secured
● It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

● Plugin is required at client browser to execute applet.


Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }

Note: class must be public because its object is created by Java Plugin software
that resides on the browser.

myapplet.html

1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }
myapplet.html

1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }

In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.

Example of animation in applet:

1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
17. }
18. }

In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the
simple example of event handling in applet that prints a message by click on the button.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }

In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html

1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }

In the above example, we have created all the controls in init() method because it is invoked
only once.

myapplet.html

1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }

In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html

1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Digital clock in Applet


Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the
simple example:
1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class DigitalClock extends Applet implements Runnable {
7.
8. Thread t = null;
9. int hours=0, minutes=0, seconds=0;
10. String timeString = "";
11.
12. public void init() {
13. setBackground( Color.green);
14. }
15.
16. public void start() {
17. t = new Thread( this );
18. t.start();
19. }
20.
21.
22. public void run() {
23. try {
24. while (true) {
25.
26. Calendar cal = Calendar.getInstance();
27. hours = cal.get( Calendar.HOUR_OF_DAY );
28. if ( hours > 12 ) hours -= 12;
29. minutes = cal.get( Calendar.MINUTE );
30. seconds = cal.get( Calendar.SECOND );
31.
32. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
33. Date date = cal.getTime();
34. timeString = formatter.format( date );
35.
36. repaint();
37. t.sleep( 1000 ); // interval given in milliseconds
38. }
39. }
40. catch (Exception e) { }
41. }
42.
43.
44. public void paint( Graphics g ) {
45. g.setColor( Color.blue );
46. g.drawString( timeString, 50, 50 );
47. }
48. }

In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html

1. <html>
2. <body>
3. <applet code="DigitalClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Analog clock in Applet


Analog clock can be created by using the Math class. Let's see the simple example:

1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class MyClock extends Applet implements Runnable {
7.
8. int width, height;
9. Thread t = null;
10. boolean threadSuspended;
11. int hours=0, minutes=0, seconds=0;
12. String timeString = "";
13.
14. public void init() {
15. width = getSize().width;
16. height = getSize().height;
17. setBackground( Color.black );
18. }
19.
20. public void start() {
21. if ( t == null ) {
22. t = new Thread( this );
23. t.setPriority( Thread.MIN_PRIORITY );
24. threadSuspended = false;
25. t.start();
26. }
27. else {
28. if ( threadSuspended ) {
29. threadSuspended = false;
30. synchronized( this ) {
31. notify();
32. }
33. }
34. }
35. }
36.
37. public void stop() {
38. threadSuspended = true;
39. }
40.
41. public void run() {
42. try {
43. while (true) {
44.
45. Calendar cal = Calendar.getInstance();
46. hours = cal.get( Calendar.HOUR_OF_DAY );
47. if ( hours > 12 ) hours -= 12;
48. minutes = cal.get( Calendar.MINUTE );
49. seconds = cal.get( Calendar.SECOND );
50.
51. SimpleDateFormat formatter
52. = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
53. Date date = cal.getTime();
54. timeString = formatter.format( date );
55.
56. // Now the thread checks to see if it should suspend itself
57. if ( threadSuspended ) {
58. synchronized( this ) {
59. while ( threadSuspended ) {
60. wait();
61. }
62. }
63. }
64. repaint();
65. t.sleep( 1000 ); // interval specified in milliseconds
66. }
67. }
68. catch (Exception e) { }
69. }
70.
71. void drawHand( double angle, int radius, Graphics g ) {
72. angle -= 0.5 * Math.PI;
73. int x = (int)( radius*Math.cos(angle) );
74. int y = (int)( radius*Math.sin(angle) );
75. g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
76. }
77.
78. void drawWedge( double angle, int radius, Graphics g ) {
79. angle -= 0.5 * Math.PI;
80. int x = (int)( radius*Math.cos(angle) );
81. int y = (int)( radius*Math.sin(angle) );
82. angle += 2*Math.PI/3;
83. int x2 = (int)( 5*Math.cos(angle) );
84. int y2 = (int)( 5*Math.sin(angle) );
85. angle += 2*Math.PI/3;
86. int x3 = (int)( 5*Math.cos(angle) );
87. int y3 = (int)( 5*Math.sin(angle) );
88. g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
89. g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
90. g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
91. }
92.
93. public void paint( Graphics g ) {
94. g.setColor( Color.gray );
95. drawWedge( 2*Math.PI * hours / 12, width/5, g );
96. drawWedge( 2*Math.PI * minutes / 60, width/3, g );
97. drawHand( 2*Math.PI * seconds / 60, width/2, g );
98. g.setColor( Color.white );
99. g.drawString( timeString, 10, height-10 );
100. }
101. }

myapplet.html

1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)

Example of using parameter in Applet:

1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }

myapplet.html

1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

Applet Communication
java.applet.AppletContext class provides the facility of communication between applets. We
provide the name of applet through the HTML file. It provides getApplet() method that returns
the object of Applet. Syntax:

1. public Applet getApplet(String name){}

Example of Applet Communication

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11. add(b);
12. b.addActionListener(this);
13. }
14.
15. public void actionPerformed(ActionEvent e){
16.
17. AppletContext ctx=getAppletContext();
18. Applet a=ctx.getApplet("app2");
19. a.setBackground(Color.yellow);
20. }
21. }

myapplet.html

1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>

Java Reflection API


Java Reflection is a process of examining or modifying the run time behavior of a class at run
time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used
The Reflection API is mainly used in:

● IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.


● Debugger
● Test Tools etc.
java.lang.Class class
The java.lang.Class class performs mainly two tasks:

● provides methods to get the metadata of a class at run time.


● provides methods to examine and change the run time behavior of a class.

Commonly used methods of Class class:


Method Description
1) public String getName() returns the class name
loads the class and
2) public static Class forName(String className)throws
returns the reference of
ClassNotFoundException
Class class.
3) public Object newInstance()throws
creates new instance.
InstantiationException,IllegalAccessException
4) public boolean isInterface() checks if it is interface.
5) public boolean isArray() checks if it is array.
6) public boolean isPrimitive() checks if it is primitive.
returns the superclass
7) public Class getSuperclass()
class reference.
returns the total number
8) public Field[] getDeclaredFields()throws SecurityException
of fields of this class.
returns the total number
9) public Method[] getDeclaredMethods()throws SecurityException
of methods of this class.
returns the total number
10) public Constructor[] getDeclaredConstructors()throws
of constructors of this
SecurityException
class.
11) public Method getDeclaredMethod(String name,Class[] returns the method class
parameterTypes)throws NoSuchMethodException,SecurityException instance.

How to get the object of Class class?


There are 3 ways to get the instance of Class class. They are as follows:

● forName() method of Class class


● getClass() method of Object class
● the .class syntax

1) forName() method of Class class

● is used to load the class dynamically.


● returns the instance of Class class.
● It should be used if you know the fully qualified name of class.This cannot be used for
primitive types.

Let's see the simple example of forName() method.

1. class Simple{}
2.
3. class Test{
4. public static void main(String args[]){
5. Class c=Class.forName("Simple");
6. System.out.println(c.getName());
7. }
8. }

Output:Simple

2) getClass() method of Object class


It returns the instance of Class class. It should be used if you know the type. Moreover, it can be
used with primitives.

1. class Simple{}
2.
3. class Test{
4. void printName(Object obj){
5. Class c=obj.getClass();
6. System.out.println(c.getName());
7. }
8. public static void main(String args[]){
9. Simple s=new Simple();
10.
11. Test t=new Test();
12. t.printName(s);
13. }
14. }
15.

Output:Simple

3) The .class syntax


If a type is available but there is no instance then it is possible to obtain a Class by appending
".class" to the name of the type.It can be used for primitive data type also.
1. class Test{
2. public static void main(String args[]){
3. Class c = boolean.class;
4. System.out.println(c.getName());
5.
6. Class c2 = Test.class;
7. System.out.println(c2.getName());
8. }
9. }

Output:boolean
Test

Determining the class object


Following methods of Class class is used to determine the class object:
1) public boolean isInterface(): determines if the specified Class object represents an interface
type.
2) public boolean isArray(): determines if this Class object represents an array class.
3) public boolean isPrimitive(): determines if the specified Class object represents a primitive
type.
Let's see the simple example of reflection api to determine the object type.

1. class Simple{}
2. interface My{}
3.
4. class Test{
5. public static void main(String args[]){
6. try{
7. Class c=Class.forName("Simple");
8. System.out.println(c.isInterface());
9.
10. Class c2=Class.forName("My");
11. System.out.println(c2.isInterface());
12.
13. }catch(Exception e){System.out.println(e);}
14.
15. }
16. }
Next Topics of Reflection API Tutorial

newInstance() method
The newInstance() method of Class class and Constructor class is used to create a new
instance of the class.
The newInstance() method of Class class can invoke zero-argument constructor whereas
newInstance() method of Constructor class can invoke any number of arguments. So Constructor
class is preferred over Class class.

Syntax of newInstance() method of Class class


public T newInstance()throws InstantiationException,IllegalAccessException
Here T is the generic version. You can think it like Object class. You will learn about generics
later.

Example of newInstance() method


Let's see the simple example to use newInstance() method.

1. class Simple{
2. void message(){System.out.println("Hello Java");}
3. }
4.
5. class Test{
6. public static void main(String args[]){
7. try{
8. Class c=Class.forName("Simple");
9. Simple s=(Simple)c.newInstance();
10. s.message();
11.
12. }catch(Exception e){System.out.println(e);}
13.
14. }
15. }

Output:Hello java
Understanding javap tool
The javap command disassembles a class file. The javap command displays information about
the fields,constructors and methods present in a class file.

Syntax to use javap tool


Let's see how to use javap tool or command.

1. javap fully_class_name

Example to use javap tool

1. javap java.lang.Object

Output:

1. Compiled from "Object.java"


2. public class java.lang.Object {
3. public java.lang.Object();
4. public final native java.lang.Class<?> getClass();
5. public native int hashCode();
6. public boolean equals(java.lang.Object);
7. protected native java.lang.Object clone() throws java.lang.CloneNotSupportedExceptio
n;
8. public java.lang.String toString();
9. public final native void notify();
10. public final native void notifyAll();
11. public final native void wait(long) throws java.lang.InterruptedException;
12. public final void wait(long, int) throws java.lang.InterruptedException;
13. public final void wait() throws java.lang.InterruptedException;
14. protected void finalize() throws java.lang.Throwable;
15. static {};
16. }

Another example to use javap tool for your class


Let's use the javap command for our java file.

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("hello java");
4. }
5. }
Now let's use the javap tool to disassemble the class file.

1. javap Simple

Output:

1. Compiled from ".java"


2. class Simple {
3. Simple();
4. public static void main(java.lang.String[]);
5. }

javap -c command
You can use the javap -c command to see disassembled code. The code that reflects the java
bytecode.

1. javap -c Simple

Output:

1. Compiled from ".java"


2. class Simple {
3. Simple();
4. Code:
5. 0: aload_0
6. 1: invokespecial #1 // Method java/lang/Object."<init>":()V
7. 4: return
8.
9. public static void main(java.lang.String[]);
10. Code:
11. 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
12. 3: ldc #3 // String hello java
13. 5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/Strin
g;)V
14. 8: return
15. }

Options of javap tool


The important options of javap tool are as follows.
Option Description
-help prints the help message.
-l prints line number and local variable
-c disassembles the code
-s prints internal type signature
-sysinfo shows system info (path, size, date, MD5 hash)
-constants shows static final constants
-version shows version information

Creating a program that works as javap tool


Following methods of java.lang.Class class can be used to display the metadata of a class.
Method Description
returns an array of Field objects reflecting all the
public Field[] getDeclaredFields()throws
fields declared by the class or interface
SecurityException
represented by this Class object.
public Constructor[] returns an array of Constructor objects reflecting
getDeclaredConstructors()throws all the constructors declared by the class
SecurityException represented by this Class object.
returns an array of Method objects reflecting all
public Method[] getDeclaredMethods()throws
the methods declared by the class or interface
SecurityException
represented by this Class object.

Example of creating javap tool


Let's create a program that works like javap tool.

1. import java.lang.reflect.*;
2.
3. public class MyJavap{
4. public static void main(String[] args)throws Exception {
5. Class c=Class.forName(args[0]);
6.
7. System.out.println("Fields........");
8. Field f[]=c.getDeclaredFields();
9. for(int i=0;i<f.length;i++)
10. System.out.println(f[i]);
11.
12. System.out.println("Constructors........");
13. Constructor con[]=c.getDeclaredConstructors();
14. for(int i=0;i<con.length;i++)
15. System.out.println(con[i]);
16.
17. System.out.println("Methods........");
18. Method m[]=c.getDeclaredMethods();
19. for(int i=0;i<m.length;i++)
20. System.out.println(m[i]);
21. }
22. }

At runtime, you can get the details of any class, it may be user-defined or pre-defined class.

Output:
Creating your own appletviewer
As you know well that appletviewer tool creates a frame and displays the output of applet in the
frame.You can also create your frame and display the applet output.

Example that works like appletviewer tool


Let's see the simple example that works like appletviewer tool. This example displays applet on
the frame.

1. import java.applet.Applet;
2. import java.awt.Frame;
3. import java.awt.Graphics;
4.
5. public class MyViewer extends Frame{
6. public static void main(String[] args) throws Exception{
7. Class c=Class.forName(args[0]);
8.
9. MyViewer v=new MyViewer();
10. v.setSize(400,400);
11. v.setLayout(null);
12. v.setVisible(true);
13.
14. Applet a=(Applet)c.newInstance();
15. a.start();
16. Graphics g=v.getGraphics();
17. a.paint(g);
18. a.stop();
19.
20. }
21.
22. }
1. //simple program of applet
2.
3. import java.applet.Applet;
4. import java.awt.Graphics;
5.
6. public class First extends Applet{
7.
8. public void paint(Graphics g){g.drawString("Welcome",50, 50);}
9. }
Output:
How to call private method from another class in java
You can call the private method from outside the class by changing the runtime behaviour of the
class.
By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private
method from any other class.

Required methods of Method class


1) public void setAccessible(boolean status) throws SecurityException sets the accessibility
of the method.
2) public Object invoke(Object method, Object... args) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException is used to invoke the method.
Required method of Class class
1) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws
NoSuchMethodException,SecurityException: returns a Method object that reflects the
specified declared method of the class or interface represented by this Class object.

Example of calling private method from another class


Let's see the simple example to call private method from another class.
File: A.java

1. public class A {
2. private void message(){System.out.println("hello java"); }
3. }

File: MethodCall.java

1. import java.lang.reflect.Method;
2. public class MethodCall{
3. public static void main(String[] args)throws Exception{
4.
5. Class c = Class.forName("A");
6. Object o= c.newInstance();
7. Method m =c.getDeclaredMethod("message", null);
8. m.setAccessible(true);
9. m.invoke(o, null);
10. }
11. }

Output:hello java

Another example to call parameterized private method from another class


Let's see the example to call parameterized private method from another class
File: A.java

1. class A{
2. private void cube(int n){System.out.println(n*n*n);}
3. }

File: M.java

1. import java.lang.reflect.*;
2. class M{
3. public static void main(String args[])throws Exception{
4. Class c=A.class;
5. Object obj=c.newInstance();
6.
7. Method m=c.getDeclaredMethod("cube",new Class[]{int.class});
8. m.setAccessible(true);
9. m.invoke(obj,4);
10. }}

Output:64

Java Date
The java.util, java.sql and java.text packages contains classes for representing date and time.
Following classes are important for dealing with date in java.

● java.util.Date class
● java.sql.Date class
● java.text.DateFormat class
● java.text.SimpleDateFormat class
● java.util.Calendar class
● java.util.GregorianCalendar class
● java.sql.Time class
● java.sql.Timestamp class
● java.util.TimeZone class

Get Current Date


There are 4 ways to print current date in java.
1st way:

1. java.util.Date date=new java.util.Date();


2. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:

1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015
3rd way:
1. long millis=System.currentTimeMillis();
2. java.sql.Date date=new java.sql.Date(millis);
3. System.out.println(date);

Output:
2015-03-27
4th way:

1. Date date=java.util.Calendar.getInstance().getTime();
2. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015

java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.
The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It
is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors
No. Constructor Description
1) Date() Creates a date object representing current date and time.
Date(long Creates a date object for the given milliseconds since January 1, 1970,
2)
milliseconds) 00:00:00 GMT.

java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
3) Object clone() returns the clone object of current date.
4) int compareTo(Date date) compares current date with given date.
5) boolean equals(Date date) compares current date with given date for equality.
6) static Date from(Instant instant) returns an instance of Date object from Instant date.
7) long getTime() returns the time represented by this date object.
8) int hashCode() returns the hash code value for this date object.
9) void setTime(long time) changes the current date and time to given time.
10) Instant toInstant() converts current date into Instant object.
11) String toString() converts this date into Instant object.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:

1. java.util.Date date=new java.util.Date();


2. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:

1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015

java.sql.Date
The java.sql.Date class represents only date in java. It inherits java.util.Date class.
The java.sql.Date instance is widely used in JDBC because it represents the date that can be
stored in database.
Some constructors and methods of java.sql.Date class has been deprecated. Here, we are not
giving list of any deprecated constructor and method.

java.sql.Date Constructor
No. Constructor Description
Date(long Creates a sql date object for the given milliseconds since January 1,
1)
milliseconds) 1970, 00:00:00 GMT.

java.sql.Date Methods
No. Method Description
1) void setTime(long time) changes the current sql date to given time.
2) Instant toInstant() converts current sql date into Instant object.
3) LocalDate toLocalDate() converts current sql date into LocalDate object.
4) String toString() converts this sql date object to a string.
5) static Date valueOf(LocalDate date) returns sql date object for the given LocalDate.
6) static Date valueOf(String date) returns sql date object for the given String.

java.sql.Date Example: get current date


Let's see the example to print date in java using java.sql.Date class.
1. public class SQLDateExample {
2. public static void main(String[] args) {
3. long millis=System.currentTimeMillis();
4. java.sql.Date date=new java.sql.Date(millis);
5. System.out.println(date);
6. }
7. }

Output:
2015-03-30

Java String to java.sql.Date Example


Let's see the example to convert string into java.sql.Date using valueOf() method.

1. import java.sql.Date;
2. public class StringToSQLDateExample {
3. public static void main(String[] args) {
4. String str="2015-03-31";
5. Date date=Date.valueOf(str);//converting string into sql date
6. System.out.println(date);
7. }
8. }

Output:
2015-03-31

Java Date Format


There are two classes for formatting date in java: DateFormat and SimpleDateFormat.
The java.text.DateFormat class provides various methods to format and parse date and time in
java in language independent manner. The DateFormat class is an abstract class. java.text.Format
is the parent class and java.text.SimpleDateFormat is the subclass of java.text.DateFormat class.
In java, converting date into string is called formatting and vice-versa parsing. In other words,
formatting means date to string and parsing means string to date.

java.text.DateFormat Fields

1. protected Calendar calendar


2. protected NumberFormat numberFormat
3. public static final int ERA_FIELD
4. public static final int YEAR_FIELD
5. public static final int MONTH_FIELD
6. public static final int DATE_FIELD
7. public static final int HOUR_OF_DAY1_FIELD
8. public static final int HOUR_OF_DAY0_FIELD
9. public static final int MINUTE_FIELD
10. public static final int SECOND_FIELD
11. public static final int MILLISECOND_FIELD
12. public static final int DAY_OF_WEEK_FIELD
13. public static final int DAY_OF_YEAR_FIELD
14. public static final int DAY_OF_WEEK_IN_MONTH_FIELD
15. public static final int WEEK_OF_YEAR_FIELD
16. public static final int WEEK_OF_MONTH_FIELD
17. public static final int AM_PM_FIELD
18. public static final int HOUR1_FIELD
19. public static final int HOUR0_FIELD
20. public static final int TIMEZONE_FIELD
21. public static final int FULL
22. public static final int LONG
23. public static final int MEDIUM
24. public static final int SHORT
25. public static final int DEFAULT

java.text.DateFormat Methods
No. Public Method Description
1) final String format(Date date) converts given Date object into string.
Date parse(String source)throws
2) converts string into Date object.
ParseException
returns time formatter with default formatting
3) static final DateFormat getTimeInstance()
style for the default locale.
static final DateFormat getTimeInstance(int returns time formatter with the given
4)
style) formatting style for the default locale.
static final DateFormat getTimeInstance(int returns time formatter with the given
5)
style, Locale locale) formatting style for the given locale.
returns date formatter with default formatting
6) static final DateFormat getDateInstance()
style for the default locale.
static final DateFormat getDateInstance(int returns date formatter with the given
7)
style) formatting style for the default locale.
static final DateFormat getDateInstance(int returns date formatter with the given
8)
style, Locale locale) formatting style for the given locale.
static final DateFormat returns date/time formatter with default
9)
getDateTimeInstance() formatting style for the default locale.
static final DateFormat returns date/time formatter with the given
10) getDateTimeInstance(int dateStyle,int date formatting style and time formatting style
timeStyle) for the default locale.
11) static final DateFormat returns date/time formatter with the given
getDateTimeInstance(int dateStyle, int date formatting style and time formatting style
timeStyle, Locale locale) for the given locale.
returns date/time formatter with short
12) static final DateFormat getInstance()
formatting style for date and time.
13) static Locale[] getAvailableLocales() returns an array of available locales.
returns an instance of Calendar for this
14) Calendar getCalendar()
DateFormat instance.
returns an instance of NumberFormat for this
15) NumberFormat getNumberFormat()
DateFormat instance.
returns an instance of TimeZone for this
16) TimeZone getTimeZone()
DateFormat instance.

Java DateFormat Example: Date to String


Let's see the simple example to format date and time in java using java.text.DateFormat class.

1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample {
4. public static void main(String[] args) {
5. Date currentDate = new Date();
6. System.out.println("Current Date: "+currentDate);
7. String dateToStr = DateFormat.getInstance().format(currentDate);
8. System.out.println("Date Format using getInstance(): "+dateToStr);
9. }
10. }

Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Let's see the full example to format date and time in java using java.text.DateFormat class.

1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample2 {
4. public static void main(String[] args) {
5. Date currentDate = new Date();
6. System.out.println("Current Date: "+currentDate);
7.
8. String dateToStr = DateFormat.getInstance().format(currentDate);
9. System.out.println("Date Format using getInstance(): "+dateToStr);
10.
11. dateToStr = DateFormat.getDateInstance().format(currentDate);
12. System.out.println("Date Format using getDateInstance(): "+dateToStr);
13.
14. dateToStr = DateFormat.getTimeInstance().format(currentDate);
15. System.out.println("Date Format using getTimeInstance(): "+dateToStr);
16.
17. dateToStr = DateFormat.getDateTimeInstance().format(currentDate);
18. System.out.println("Date Format using getDateTimeInstance(): "+dateToStr);
19.
20. dateToStr = DateFormat.getTimeInstance(DateFormat.SHORT).format(currentDate);

21. System.out.println("Date Format using getTimeInstance(DateFormat.SHORT): "+dat


eToStr);
22.
23. dateToStr = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(currentDat
e);
24. System.out.println("Date Format using getTimeInstance(DateFormat.MEDIUM): "+d
ateToStr);
25.
26. dateToStr = DateFormat.getTimeInstance(DateFormat.LONG).format(currentDate);

27. System.out.println("Date Format using getTimeInstance(DateFormat.LONG): "+date


ToStr);
28.
29. dateToStr = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHO
RT).format(currentDate);
30. System.out.println("Date Format using getDateTimeInstance(DateFormat.LONG,Dat
eFormat.SHORT): "+dateToStr);
31.
32. }
33. }

Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Date Format using getDateInstance(): 31 Mar, 2015
Date Format using getTimeInstance(): 2:37:23 PM
Date Format using getDateTimeInstance(): 31 Mar, 2015 2:37:23 PM
Date Format using getTimeInstance(DateFormat.SHORT): 2:37 PM
Date Format using getTimeInstance(DateFormat.MEDIUM): 2:37:23 PM
Date Format using getTimeInstance(DateFormat.LONG): 2:37:23 PM IST
Date Format using getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT): 31
March, 2015 2:37 PM

Java DateFormat Example: String to Date


Let's see the simple example to convert string into date using java.text.DateFormat class.

1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample3 {
4. public static void main(String[] args)throws Exception {
5. Date d = DateFormat.getDateInstance().parse("31 Mar, 2015");
6. System.out.println("Date is: "+d);
7. }
8. }

Output:
Date is: Tue Mar 31 00:00:00 IST 2015

Java SimpleDateFormat
The java.text.SimpleDateFormat class provides methods to format and parse date and time in
java. The SimpleDateFormat is a concrete class for formatting and parsing date which inherits
java.text.DateFormat class.
Notice that formatting means converting date to string and parsing means converting string
to date.

Java SimpleDateFormat Example: Date to String


Let's see the simple example to format date in java using java.text.SimpleDateFormat class.

1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class SimpleDateFormatExample {
4. public static void main(String[] args) {
5. Date date = new Date();
6. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
7. String strDate= formatter.format(date);
8. System.out.println(strDate);
9. }
10. }

Output:
13/04/2015

Note: M (capital M) represents month and m (small m) represents minute in


java.
Let's see the full example to format date and time in java using java.text.SimpleDateFormat
class.

1. import java.text.ParseException;
2. import java.text.SimpleDateFormat;
3. import java.util.Date;
4. import java.util.Locale;
5. public class SimpleDateFormatExample2 {
6. public static void main(String[] args) {
7. Date date = new Date();
8. SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
9. String strDate = formatter.format(date);
10. System.out.println("Date Format with MM/dd/yyyy : "+strDate);
11.
12. formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
13. strDate = formatter.format(date);
14. System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
15.
16. formatter = new SimpleDateFormat("dd MMMM yyyy");
17. strDate = formatter.format(date);
18. System.out.println("Date Format with dd MMMM yyyy : "+strDate);
19.
20. formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
21. strDate = formatter.format(date);
22. System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
23.
24. formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
25. strDate = formatter.format(date);
26. System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
27. }
28. }

Output:
Date Format with MM/dd/yyyy : 04/13/2015
Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26
Date Format with dd MMMM yyyy : 13 April 2015
Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time
Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST

Java SimpleDateFormat Example: String to Date


Let's see the simple example to convert string into date using java.text.SimpleDateFormat
class.

1. import java.text.ParseException;
2. import java.text.SimpleDateFormat;
3. import java.util.Date;
4. public class SimpleDateFormatExample3 {
5. public static void main(String[] args) {
6. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
7. try {
8. Date date = formatter.parse("31/03/2015");
9. System.out.println("Date is: "+date);
10. } catch (ParseException e) {e.printStackTrace();}
11. }
12. }

Output:
Date is: Tue Mar 31 00:00:00 IST 2015

Java Get Current Date


There are many ways to get current date and time in java. There are 3 classes that can be used to
get current date.

1. java.util.Date class
2. java.sql.Date class
3. java.util.Calendar class

1) Get Current Date by java.util.Date class


By printing the instance of java.util.Date class, you can print current date and time in java. There
are two ways to do so.
1st way:

1. java.util.Date date=new java.util.Date();


2. System.out.println(date);

2nd way:

1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);

Output:
Thu Mar 26 08:22:02 IST 2015

2) Get Current Date by java.sql.Date class


By printing the instance of java.sql.Date class, you can print current date in java. It doesn't print
time. This date instance is generally used to save current date in database.

1. long millis=System.currentTimeMillis();
2. java.sql.Date date=new java.sql.Date(millis);
3. System.out.println(date);

Output:
2015-03-26

3) Get Current Date by java.util.Calendar class


Calendar class can be used to get the instance of Date class. The getTime() method of Calendar
class returns the instance of java.util.Date. The Calendar.getInstance() method returns the
instance of Calendar class.

1. Date date=java.util.Calendar.getInstance().getTime();
2. System.out.println(date);

Output:
Thu Mar 26 08:22:02 IST 2015

Note: It is recommended to use Calendar class for getting current date and time.

Java String to int


We can convert String to int in java using Integer.parseInt() method.

Scenario
It is generally used if we have to perform mathematical operations on the string that contains
number. Whenever we get data from textfield or textarea, entered data is received as a string. If
entered data is integer, we need to convert string to int. To do so, we use Integer.parseInt()
method.

Signature
The parseInt() is the static method of Integer class. The signature of parseInt() method is given
below:

1. public static int parseInt(String s)

Java String to int Example


Let's see the simple code to convert string to int in java.

1. int i=Integer.parseInt("200");

Let's see the simple example of converting String to int in java.

1. public class StringToIntExample{


2. public static void main(String args[]){
3. String s="200";
4. int i=Integer.parseInt(s);
5. System.out.println(s+100);//200100 because + is string concatenation operator
6. System.out.println(i+100);//300 because + is binary plus operator
7. }}

Output:
200100
300

Java int to String


We can convert int to String in java using String.valueOf() and Integer.toString() methods.

Scenario
It is generally used if we have to display number in textfield because everything is displayed as a
string in form.

1) String.valueOf()
The String.valueOf() method converts int to String. The valueOf() is the static method of String
class. The signature of valueOf() method is given below:

1. public static String valueOf(int i)

Java int to String Example using String.valueOf()


Let's see the simple code to convert int to String in java.

1. int i=10;
2. String s=String.valueOf(i);//Now it will return "10"

Let's see the simple example of converting String to int in java.

1. public class IntToStringExample1{


2. public static void main(String args[]){
3. int i=200;
4. String s=String.valueOf(i);
5. System.out.println(i+100);//300 because + is binary plus operator
6. System.out.println(s+100);//200100 because + is string concatenation operator
7. }}
Output:
300
200100

2) Integer.toString()
The Integer.toString() method converts int to String. The toString() is the static method of
Integer class. The signature of toString() method is given below:

1. public static String toString(int i)

Java int to String Example using Integer.toString()


Let's see the simple code to convert int to String in java using Integer.toString() method.

1. int i=10;
2. String s=Integer.toString(i);//Now it will return "10"

Let's see the simple example of converting String to int in java.

1. public class IntToStringExample2{


2. public static void main(String args[]){
3. int i=200;
4. String s=Integer.toString(i);
5. System.out.println(i+100);//300 because + is binary plus operator
6. System.out.println(s+100);//200100 because + is string concatenation operator
7. }}

Output:
300
200100

Java String to long


We can convert String to long in java using Long.parseLong() method.

Scenario
It is generally used if we have to perform mathematical operations on the string that contains
long number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is long, we need to convert string to long. To do so, we use
Long.parseLong() method.

Signature
The parseLong() is the static method of Long class. The signature of parseLong() method is
given below:
1. public static long parseLong(String s)

Java String to long Example


Let's see the simple code to convert string to long in java.

1. long l=Long.parseLong("200");

Let's see the simple example of converting String to long in java.

1. public class StringToLongExample{


2. public static void main(String args[]){
3. String s="9990449935";
4. long l=Long.parseLong(s);
5. System.out.println(l);
6. }}

Output:
9990449935

Java long to String


We can convert long to String in java using String.valueOf() and Long.toString() methods.

Scenario
It is generally used if we have to display long number in textfield because everything is
displayed as a string in form.

1) String.valueOf()
The String.valueOf() is an overloaded method. It can be used to convert long to String. The
valueOf() is the static method of String class. The signature of valueOf() method is given below:

1. public static String valueOf(long i)

Java long to String Example using String.valueOf()


Let's see the simple code to convert int to String in java.

1. long i=9993939399L;//L is the suffix for long


2. String s=String.valueOf(i);//Now it will return "9993939399"

Let's see the simple example of converting String to int in java.


1. public class LongToStringExample1{
2. public static void main(String args[]){
3. long i=9993939399L;
4. String s=String.valueOf(i);
5. System.out.println(s);
6. }}

Output:
9993939399

2) Long.toString()
The Long.toString() method converts long to String. The toString() is the static method of Long
class. The signature of toString() method is given below:

1. public static String toString(long i)

Java long to String Example using Long.toString()


Let's see the simple code to convert int to String in java using Long.toString() method.

1. long i=9993939399L;
2. String s=Long.toString(i);//Now it will return "9993939399"

Let's see the simple example of converting String to int in java.

1. public class LongToStringExample2{


2. public static void main(String args[]){
3. long i=9993939399L;
4. String s=Long.toString(i);
5. System.out.println(s);
6. }}

Output:
9993939399

Java String to float


We can convert String to float in java using Float.parseFloat() method.

Scenario
It is generally used if we have to perform mathematical operations on the string that contains
float number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is float, we need to convert string to float. To do so, we use
Float.parseFloat() method.

Signature
The parseFloat() is the static method of Float class. The signature of parseFloat() method is
given below:

1. public static int parseFloat(String s)

Java String to float Example


Let's see the simple code to convert string to float in java.

1. float f=Float.parseFloat("23.6");

Let's see the simple example of converting String to float in java.

1. public class StringToFloatExample{


2. public static void main(String args[]){
3. String s="23.6";
4. float f=Float.parseFloat("23.6");
5. System.out.println(f);
6. }}

Output:
23.6

Java String to double


We can convert String to double in java using Double.parseDouble() method.

Scenario
It is generally used if we have to perform mathematical operations on the string that contains
double number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is double, we need to convert string to double. To do so, we use
Double.parseDouble() method.

Signature
The parseDouble() is the static method of Double class. The signature of parseDouble() method
is given below:

1. public static double parseDouble(String s)


Java String to double Example
Let's see the simple code to convert string to double in java.

1. double d=Double.parseDouble("23.6");

Let's see the simple example of converting String to double in java.

1. public class StringToDoubleExample{


2. public static void main(String args[]){
3. String s="23.6";
4. double d=Double.parseDouble("23.6");
5. System.out.println(d);
6. }}

Java String to Date


We can convert String to Date in java using parse() method of DateFormat and
SimpleDateFormat classes. To learn this concept well, you should visit DateFormat and
SimpleDateFormat classes.

Java String to Date Example


Let's see the simple code to convert String to Date in java.

1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class StringToDateExample1 {
4. public static void main(String[] args)throws Exception {
5. String sDate1="31/12/1998";
6. Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
7. System.out.println(sDate1+"\t"+date1);
8. }
9. }

Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
Let's see another code to convert different types of string to Date in java.

1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class StringToDateExample1 {
4. public static void main(String[] args)throws Exception {
5. String sDate1="31/12/1998";
6. String sDate2 = "31-Dec-1998";
7. String sDate3 = "12 31, 1998";
8. String sDate4 = "Thu, Dec 31 1998";
9. String sDate5 = "Thu, Dec 31 1998 23:37:50";
10. String sDate6 = "31-Dec-1998 23:37:50";
11. SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
12. SimpleDateFormat formatter2=new SimpleDateFormat("dd-MMM-yyyy");
13. SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");
14. SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");
15. SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss")
;
16. SimpleDateFormat formatter6=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
17. Date date1=formatter1.parse(sDate1);
18. Date date2=formatter2.parse(sDate2);
19. Date date3=formatter3.parse(sDate3);
20. Date date4=formatter4.parse(sDate4);
21. Date date5=formatter5.parse(sDate5);
22. Date date6=formatter6.parse(sDate6);
23. System.out.println(sDate1+"\t"+date1);
24. System.out.println(sDate2+"\t"+date2);
25. System.out.println(sDate3+"\t"+date3);
26. System.out.println(sDate4+"\t"+date4);
27. System.out.println(sDate5+"\t"+date5);
28. System.out.println(sDate6+"\t"+date6);
29. }
30. }

Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
31-Dec-1998 Thu Dec 31 00:00:00 IST 1998
12 31, 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
31-Dec-1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection in java


Collection represents a single unit of objects i.e. a group.

What is framework in java

● provides readymade architecture.


● represents set of classes and interface.
● is optional.

What is Collection framework


Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Do You Know ?

● What are the two ways to iterate the elements of a collection ?


● What is the difference between ArrayList and LinkedList classes in collection
framework?
● What is the difference between ArrayList and Vector classes in collection framework?
● What is the difference between HashSet and HashMap classes in collection framework?
● What is the difference between HashMap and Hashtable class?
● What is the difference between Iterator and Enumeration interface in collection
framework?
● How can we sort the elements of an object. What is the difference between Comparable
and Comparator interfaces?
● What does the hashcode() method ?

li>What is the difference between java collection and java collections ?


Hierarchy of Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains all the classes
and interfaces for Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:
No. Method Description
public boolean add(Object
1 is used to insert an element in this collection.
element)
public boolean addAll(collection is used to insert the specified collection elements in the
2
c) invoking collection.
public boolean remove(Object
3 is used to delete an element from this collection.
element)
public boolean is used to delete all the elements of specified collection
4
removeAll(Collection c) from the invoking collection.
public boolean is used to delete all the elements of invoking collection
5
retainAll(Collection c) except the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
public boolean contains(object
8 is used to search an element.
element)
public boolean
9 is used to search the specified collection in this collection.
containsAll(Collection c)
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
public boolean equals(Object
13 matches two collection.
element)
14 public int hashCode() returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.


2. public object next() it returns the element and moves the cursor pointer to the next
element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely
used.

What we are going to learn in Java Collections Framework

1. ArrayList class
2. LinkedList class
3. ListIterator interface
4. HashSet class
5. LinkedHashSet class
6. TreeSet class
7. PriorityQueue class
8. Map interface
9. HashMap class
10. LinkedHashMap class
11. TreeMap class
12. Hashtable class
13. Sorting
14. Comparable interface
15. Comparator interface
16. Properties class in Java

Java ArrayList class


● Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList
class and implements List interface.
● Java ArrayList class can contain duplicate elements.
● Java ArrayList class maintains insertion order.
● Java ArrayList class is non synchronized.
● Java ArrayList allows random access because array works at the index basis.
● In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Java Non-generic Vs Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.

1. ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile time
error.

Example of Java ArrayList class

1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Ravi
Vijay
Ravi
Ajay

Two ways to iterate the elements of collection in java

1. By Iterator interface.
2. By for-each loop.

In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.

Iterating the elements of Collection by for-each loop

1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }

Ravi
Vijay
Ravi
Ajay

User-defined class objects in Java ArrayList

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8.
9. ArrayList<Student> al=new ArrayList<Student>();//creating arraylist
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }

101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method

1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Sonoo");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20. }
21. }

Ravi
Vijay
Ajay
Sonoo
Hanumat

Example of removeAll() method

1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21.
22. }
23. }

iterating the elements after removing the elements of al2...


Vijay
Ajay

Example of retainAll() method

1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11.
12. al.retainAll(al2);
13.
14. System.out.println("iterating the elements after retaining the elements of al2...");
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19. }
20. }

iterating the elements after retaining the elements of al2...


Ravi

Java LinkedList class


● Java LinkedList class uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
● Java LinkedList class can contain duplicate elements.
● Java LinkedList class maintains insertion order.
● Java LinkedList class is non synchronized.
● In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
● Java LinkedList class can be used as list, stack or queue.

Java LinkedList Example

1. import java.util.*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:Ravi
Vijay
Ravi
Ajay
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are
non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
1) ArrayList internally uses dynamic array to store LinkedList internally uses doubly linked list
the elements. to store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is removed ArrayList because it uses doubly linked list so
from the array, all the bits are shifted in memory. no bit shifting is required in memory.
LinkedList class can act as a list and queue
3) ArrayList class can act as a list only because it
both because it implements List and Deque
implements List only.
interfaces.
4) ArrayList is better for storing and accessing
LinkedList is better for manipulating data.
data.

Example of ArrayList and LinkedList in Java


Let's see a simple example where we are using ArrayList and LinkedList both.

1. import java.util.*;
2. class TestArrayLinked{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. List<String> al2=new LinkedList<String>();//creating linkedlist
12. al2.add("James");//adding object in linkedlist
13. al2.add("Serena");
14. al2.add("Swati");
15. al2.add("Junaid");
16.
17. System.out.println("arraylist: "+al);
18. System.out.println("linkedlist: "+al2);
19. }
20. }

Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

Java List Interface


List Interface is the subinterface of Collection.It contains methods to insert and delete elements
in index basis.It is a factory of ListIterator interface.

Commonly used methods of List Interface:

1. public void add(int index,Object element);


2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

Java ListIterator Interface


ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used methods of ListIterator Interface:

1. public boolean hasNext();


2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();

Example of ListIterator Interface:

1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Amit");
7. al.add("Vijay");
8. al.add("Kumar");
9. al.add(1,"Sachin");
10.
11. System.out.println("element at 2nd position: "+al.get(2));
12.
13. ListIterator<String> itr=al.listIterator();
14.
15. System.out.println("traversing elements in forward direction...");
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19.
20.
21. System.out.println("traversing elements in backward direction...");
22. while(itr.hasPrevious()){
23. System.out.println(itr.previous());
24. }
25. }
26. }

Output:element at 2nd position: Vijay


traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

Java HashSet class


● uses hashtable to store the elements.It extends AbstractSet class and implements Set
interface.
● contains unique elements only.

Difference between List and Set:


List can contain duplicate elements whereas Set contains unique elements only.
Hierarchy of HashSet class:

Example of HashSet class:

1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4.
5. HashSet<String> al=new HashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ajay
Vijay
Ravi

Java LinkedHashSet class:


● contains unique elements only like HashSet. It extends HashSet class and implements
Set interface.
● maintains insertion order.

Hierarchy of LinkedHashSet class:

Example of LinkedHashSet class:

1. import java.util.*;
2. class TestCollection10{
3. public static void main(String args[]){
4.
5. LinkedHashSet<String> al=new LinkedHashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:>Ravi
Vijay
Ajay

Java TreeSet class


● contains unique elements only like HashSet. The TreeSet class implements NavigableSet
interface that extends the SortedSet interface.
● maintains ascending order.
Hierarchy of TreeSet class:

Example of TreeSet class:

1. import java.util.*;
2. class TestCollection11{
3. public static void main(String args[]){
4.
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:Ajay
Ravi
Vijay

Java Queue Interface


The Queue interface basically orders the element in FIFO(First In First Out)manner.

Methods of Queue Interface :

1. public boolean add(object);


2. public boolean offer(object);
3. public remove();
4. public poll();
5. public element();
6. public peek();

PriorityQueue class:
The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner.

Example of PriorityQueue:

1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4.
5. PriorityQueue<String> queue=new PriorityQueue<String>();
6. queue.add("Amit");
7. queue.add("Vijay");
8. queue.add("Karan");
9. queue.add("Jai");
10. queue.add("Rahul");
11.
12. System.out.println("head:"+queue.element());
13. System.out.println("head:"+queue.peek());
14.
15. System.out.println("iterating the queue elements:");
16. Iterator itr=queue.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20.
21. queue.remove();
22. queue.poll();
23.
24. System.out.println("after removing two elements:");
25. Iterator<String> itr2=queue.iterator();
26. while(itr2.hasNext()){
27. System.out.println(itr2.next());
28. }
29.
30. }
31. }

Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Java Map Interface


A map contains values based on the key i.e. key and value pair.Each pair is known as an
entry.Map contains only unique elements.

Commonly used methods of Map interface:

1. public Object put(object key,Object value): is used to insert an entry in this map.
2. public void putAll(Map map):is used to insert the specified map in this map.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. public boolean containsKey(Object key):is used to search the specified key from this
map.
6. public boolean containsValue(Object value):is used to search the specified value from
this map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.
Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to
get key and value.

Methods of Entry interface:

1. public Object getKey(): is used to obtain key.


2. public Object getValue():is used to obtain value.

Java HashMap class


● A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
● It contains only unique elements.
● It may have one null key and multiple null values.
● It maintains no order.

Hierarchy of HashMap class:

Example of HashMap class:

1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4.
5. HashMap<Integer,String> hm=new HashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }

Output:102 Rahul
100 Amit
101 Vijay

Java LinkedHashMap class


● A LinkedHashMap contains values based on the key. It implements the Map interface
and extends HashMap class.
● It contains only unique elements.
● It may have one null key and multiple null values.
● It is same as HashMap instead maintains insertion order.

Hierarchy of LinkedHashMap class:


Example of LinkedHashMap class:

1. import java.util.*;
2. class TestCollection14{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }

Output:100 Amit
101 Vijay
103 Rahul

Java TreeMap class


● A TreeMap contains values based on the key. It implements the NavigableMap interface
and extends AbstractMap class.
● It contains only unique elements.
● It cannot have null key but can have multiple null values.
● It is same as HashMap instead maintains ascending order.
Hierarchy of TreeMap class:

Example of TreeMap class:

1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4.
5. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }

Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
What is difference between HashMap and TreeMap?
1) HashMap is can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.

Java Hashtable class


● A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is
identified by calling the hashcode() method.A Hashtable contains values based on the
key. It implements the Map interface and extends Dictionary class.
● It contains only unique elements.
● It may have not have any null key or value.
● It is synchronized.

Example of Hashtable:

1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }

Output:103 Rahul
102 Ravi
101 Vijay
100 Amit

Difference between HashMap and Hashtable


HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe and can't Hashtable is synchronized. It is
be shared between many threads without proper thread-safe and can be shared
synchronization code. with many threads.
Hashtable doesn't allow any
2) HashMap allows one null key and multiple null values.
null key or value.
3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as synchronized by calling this Hashtable is internally
code synchronized and can't be
Map m = Collections.synchronizedMap(hashMap); unsynchronized.
Hashtable is traversed by
6) HashMap is traversed by Iterator.
Enumerator and Iterator.
Enumerator in Hashtable is not
7) Iterator in HashMap is fail-fast.
fail-fast.
Hashtable inherits Dictionary
8) HashMap inherits AbstractMap class.
class.

Sorting
We can sort the elements of:

1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements


public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So
if you store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects

1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Output:Mukesh
Saurav
Tahir
Viru

Example of Sorting the elements of List that contains Wrapper class objects

1. import java.util.*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Output:101
201
230
Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is found in
java.lang package and contains only one method named compareTo(Object).It provide only
single sorting sequence i.e. you can sort the elements on based on single datamember only.For
instance it may be either rollno,name,age or anything else.

Syntax:
public int compareTo(Object obj): is used to compare the current object with the specified
object.

We can sort the elements of:

1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements


public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So
if you store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains user-defined class objects
on age basis
Student.java

1. class Student implements Comparable{


2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Object obj){
12. Student st=(Student)obj;
13. if(age==st.age)
14. return 0;
15. else if(age>st.age)
16. return 1;
17. else
18. return -1;
19. }
20.
21. }

Simple.java

1. import java.util.*;
2. import java.io.*;
3.
4. class TestSort3{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. Collections.sort(al);
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. Student st=(Student)itr.next();
16. System.out.println(st.rollno+""+st.name+""+st.age);
17. }
18. }
19. }

Output:105 Jai 21
101 Vijay 23
106 Ajay 27

Comparator interface
Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements based on any data member.
For instance it may be on rollno, name, age or anything else.

Syntax of compare method


public int compare(Object obj1,Object obj2): compares the first object with second object.

Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.
Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements


public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.

Example of sorting the elements of List that contains user-defined class


objects on the basis of age and name
In this example, we have created 4 java classes:

1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java

Student.java
This class contains three fields rollno, name and age and a parameterized constructor.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.

1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }

NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }

Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }

Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27

Properties class in Java


The properties object contains key and value pair both as a string. It is the subclass of
Hashtable.
It can be used to get property value based on the property key. The Properties class provides
methods to get data from properties file and store data into properties file. Moreover, it can be
used to get properties of system.

Advantage of properties file


Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.
Methods of Properties class
The commonly used methods of Properties class are given below.
Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String
sets the property in the properties object.
value)
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String
writes the properties in the OutputStream object.
comment)
storeToXML(OutputStream os, String writers the properties in the writer object for
comment) generating xml document.
public void storeToXML(Writer w, String writers the properties in the writer object for
comment, String encoding) generating xml document with specified encoding.

Example of Properties class to get information from properties file


To get information from the properties file, create the properties file first.
db.properties

1. user=system
2. password=oracle

Now, lets create the java class to read the data from the properties file.
Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }

Output:system
oracle
Now if you change the value of the properties file, you don't need to compile the java class
again. That means no maintenance problem.

Example of Properties class to get all the system properties


By System.getProperties() method we can get all the properties of system. Let's create the class
that gets information from the system properties.
Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }

Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........

Example of Properties class to create properties file


Now lets write the code to create the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Sonoo Jaiswal");
8. p.setProperty("email","[email protected]");
9.
10. p.store(new FileWriter("info.properties"),"Java Properties Example");
11.
12. }
13. }

Let's see the generated properties file.


info.properties

1. #Java Properties Example


2. #Thu Oct 03 22:35:53 IST 2013
3. [email protected]
4. name=Sonoo Jaiswal

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of
Vector increments 100% means doubles the array size if
current array size if number of
total number of element exceeds than its capacity.
element exceeds from its capacity.
3) ArrayList is not a legacy class, it
Vector is a legacy class.
is introduced in JDK 1.2.
Vector is slow because it is synchronized i.e. in
4) ArrayList is fast because it is non- multithreading environment, it will hold the other threads
synchronized. in runnable or non-runnable state until current thread
releases the lock of object.
5) ArrayList uses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.

Example of Java ArrayList


Let's see a simple example where we are using ArrayList to store and traverse the elements.
1. import java.util.*;
2. class TestArrayList21{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Sonoo");//adding object in arraylist
7. al.add("Michael");
8. al.add("James");
9. al.add("Andy");
10. //traversing elements using Iterator
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:
Sonoo
Michael
James
Andy

Example of Java Vector


Let's see a simple example of java Vector class that uses Enumeration interface.

1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }

Output:
umesh
irfan
kumar

Java JDBC Tutorial


Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
Do You Know

● How to connect Java application with Oracle and Mysql database using JDBC?
● What is the difference between Statement and PreparedStatement interface?
● How to print total numbers of tables and views of a database using JDBC ?
● How to store and retrieve images from Oracle database using JDBC?
● How to store and retrieve files from Oracle database using JDBC?

What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc
Topics in Java JDBC Tutorial
2) JDBC Drivers
In this JDBC tutorial, we will learn 4 types of JDBC drivers, their advantages and disadvantages.

3) 5 Steps to connect to the database


In this JDBC tutorial, we will see the 5 steps to connect to the database in java using JDBC.

4) Connectivity with Oracle using JDBC


In this JDBC tutorial, we will connect a simple java program with the oracle database.

5) Connectivity with MySQL using JDBC


In this JDBC tutorial, we will connect a simple java program with the mysql database.

6) Connectivity with Access without DSN


Let's connect java application with access database with and without DSN.

7) DriverManager class
In this JDBC tutorial, we will learn what does the DriverManager class and what are its methods.

8) Connection interface
In this JDBC tutorial, we will learn what is Connection interface and what are its methods.

9) Statement interface
In this JDBC tutorial, we will learn what is Statement interface and what are its methods.

10) ResultSet interface


In this JDBC tutorial, we will learn what is ResultSet interface and what are its methods.
Moreover, we will learn how we can make the ResultSet scrollable.

11) PreparedStatement Interface


In this JDBC tutorial, we will learn what is benefit of PreparedStatement over Statement
interface. We will see examples to insert, update or delete records using the PreparedStatement
interface.

12) ResultSetMetaData interface


In this JDBC tutorial, we will learn how we can get the metadata of a table.
13) DatabaseMetaData interface
In this JDBC tutorial, we will learn how we can get the metadata of a database.

14) Storing image in Oracle


Let's learn how to store image in the oracle database using JDBC.

15) Retrieving image from Oracle


Let's see the simple example to retrieve image from the oracle database using JDBC.

16) Storing file in Oracle


Let's see the simple example to store file in the oracle database using JDBC.

17) Retrieving file from Oracle


Let's see the simple example to retrieve file from the oracle database using JDBC.

18) CallableStatement
Let's see the code to call stored procedures and functions using CallableStatement.

19) Transaction Management using JDBC


Let's see the simple example to use transaction management using JDBC.

20) Batch Statement using JDBC


Let's see the code to execute batch of queries.

21) JDBC RowSet


Let's see the working of new JDBC RowSet interface.

JDBC Driver

JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged
because of thin driver.

Advantages:

● easy to use.
● can be easily connected to any database.

Disadvantages:

● Performance degraded because JDBC method call is converted into the ODBC function
calls.
● The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:

● performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

● The Native driver needs to be installed on the each client machine.


● The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:

● No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

● Network support is required on client machine.


● Requires database-specific coding to be done in the middle tier.
● Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:

● Better performance than all other drivers.


● No software is required at client side or server side.

Disadvantage:

● Drivers depends on the Database.

5 Steps to connect to the database in java

There are 5 steps to connect any java application with the database in java using JDBC. They are
as follows:

● Register the driver class


● Creating connection
● Creating statement
● Executing queries
● Closing connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object

1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection

1. con.close();

Example to connect to the Oracle database


For connecting java application with the oracle database, you need to follow 5 steps to perform
database connectivity. In this example we are using Oracle10g as the database. So we need to
know following informations for the oracle database:

1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is
the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all
these informations from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle database.
Let's first create a table in oracle database.
1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database


In this example, system is the username and oracle is the password of the Oracle database.

1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }

The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
download the jar file ojdbc14.jar
Two ways to load the jar file:

1. paste the ojdbc14.jar file in jre/lib/ext folder


2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.

2) set classpath:
There are two ways to set the classpath:

● temporary
● permanent

How to set the temporary classpath:


Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

Example to connect to the mysql database


For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password.

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:mysql://localhost:3306/sonoo","root","root");
9.
10. //here sonoo is database name, root is username and password
11.
12. Statement stmt=con.createStatement();
13.
14. ResultSet rs=stmt.executeQuery("select * from emp");
15.
16. while(rs.next())
17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }

The above example will fetch all the records of emp table.

To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
download the jar file mysql-connector.jar
Two ways to load the jar file:

1. paste the mysqlconnector.jar file in jre/lib/ext folder


2. set classpath

1) paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) set classpath:
There are two ways to set the classpath:

● temporary
● permament

How to set the temporary classpath


open comman prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Connectivity with Access without DSN


There are two ways to connect java application with the access database.

1. Without DSN (Data Source Name)


2. With DSN

Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.

Example to Connect Java Application with access without DSN


In this example, we are going to connect the java program with the access database. In such case,
we have created the login table in the access database. There is only one column in the table
named name. Let's get all the name of the login table.

1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the current directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";
9.
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection c=DriverManager.getConnection(url);
12. Statement st=c.createStatement();
13. ResultSet rs=st.executeQuery("select * from login");
14.
15. while(rs.next()){
16. System.out.println(rs.getString(1));
17. }
18.
19. }catch(Exception ee){System.out.println(ee);}
20.
21. }}

Example to Connect Java Application with access with DSN


Connectivity with type1 driver is not considered good. To connect java application with type1
driver, create DSN first, here we are assuming your dsn name is mydsn.

1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1));
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}
DriverManager class:
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().

Commonly used methods of DriverManager class:


is used to register the given driver with
1) public static void registerDriver(Driver driver):
DriverManager.
2) public static void deregisterDriver(Driver is used to deregister the given driver (drop
driver): the driver from the list) with DriverManager.
3) public static Connection getConnection(String is used to establish the connection with the
url): specified url.
4) public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url, username and password.

Connection interface:
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be
used to get the object of Statement and DatabaseMetaData. The Connection interface provide
many methods for transaction management like commit(),rollback() etc.

By default, connection commits the changes after executing queries.

Commonly used methods of Connection interface:


1) public Statement createStatement(): creates a statement object that can be used to execute
SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is
true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.

Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.

Example of Statement interface


Let’s see the simple example of Statement interface to insert, update and delete the record.

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7. Statement stmt=con.createStatement();
8.
9. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
10. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 wher
e id=33");
11. int result=stmt.executeUpdate("delete from emp765 where id=33");
12.
13. System.out.println(result+" records affected");
14. con.close();
15. }}

ResultSet interface
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor
points to before the first row.

By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:

1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
is used to move the cursor to the one row next from the
1) public boolean next():
current position.
is used to move the cursor to the one row previous from the
2) public boolean previous():
current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int is used to move the cursor to the specified row number in the
row): ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row number in the
row): ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.
8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
10) public String getString(String is used to return the data of specified column name of the
columnName): current row as String.

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int
sets the integer value to the given parameter index.
value)
public void setString(int paramIndex,
sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, float
sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex,
sets the double value to the given parameter index.
double value)
executes the query. It is used for create, drop, insert,
public int executeUpdate()
update, delete etc.
executes the select query. It returns an instance of
public ResultSet executeQuery()
ResultSet.

Example of PreparedStatement interface that inserts the record


First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }

Example of PreparedStatement interface that updates the record

1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?")


;
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
Example of PreparedStatement interface that deletes the record

1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");


2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");

Example of PreparedStatement interface that retrieve the records of a table

1. PreparedStatement stmt=con.prepareStatement("select * from emp");


2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

Example of PreparedStatement to insert records until user press n

1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println("enter id:");
14. int id=Integer.parseInt(br.readLine());
15. System.out.println("enter name:");
16. String name=br.readLine();
17. System.out.println("enter salary:");
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+" records affected");
25.
26. System.out.println("Do you want to continue: y/n");
27. String s=br.readLine();
28. if(s.startsWith("n")){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}

ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.

Commonly used methods of ResultSetMetaData interface


Method Description
it returns the total number of columns in
public int getColumnCount()throws SQLException
the ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

How to get the object of ResultSetMetaData:


The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.
Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException
Example of ResultSetMetaData interface :

1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from emp");
11. ResultSet rs=ps.executeQuery();
12.
13. ResultSetMetaData rsmd=rs.getMetaData();
14.
15. System.out.println("Total columns: "+rsmd.getColumnCount());
16. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
17. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1))
;
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }

Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

DatabaseMetaData interface:
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.

Commonly used methods of DatabaseMetaData interface


● public String getDriverName()throws SQLException: it returns the name of the JDBC
driver.
● public String getDriverVersion()throws SQLException: it returns the version number of
the JDBC driver.
● public String getUserName()throws SQLException: it returns the username of the
database.
● public String getDatabaseProductName()throws SQLException: it returns the product
name of the database.
● public String getDatabaseProductVersion()throws SQLException: it returns the product
version of the database.
● public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description of the
tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE,
SYNONYM etc.

How to get the object of DatabaseMetaData:


The getMetaData() method of Connection interface returns the object of DatabaseMetaData.
Syntax:

1. public DatabaseMetaData getMetaData()throws SQLException

Simple Example of DatabaseMetaData interface :

1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11.
12. System.out.println("Driver Name: "+dbmd.getDriverName());
13. System.out.println("Driver Version: "+dbmd.getDriverVersion());
14. System.out.println("UserName: "+dbmd.getUserName());
15. System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
16. System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }

Output:Driver Name: Oracle JDBC Driver


Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production

Example of DatabaseMetaData interface that prints total number of tables :

1. import java.sql.*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"TABLE"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }

Example of DatabaseMetaData interface that prints total number of views :

1. import java.sql.*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"VIEW"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }

Example to store image in Oracle database


You can store images in the database in java by the help of PreparedStatement interface.
The setBinaryStream() method of PreparedStatement is used to set Binary information into the
parameterIndex.

Signature of setBinaryStream method


The syntax of setBinaryStream() method is given below:

1. 1) public void setBinaryStream(int paramIndex,InputStream stream)


2. throws SQLException
3. 2) public void setBinaryStream(int paramIndex,InputStream stream,long length)
4. throws SQLException

For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
For example:

1. CREATE TABLE "IMGTABLE"


2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /

Let's write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for the
location of image. You can change it according to the image location.

1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
21. }

If you see the table, record is stored in the database but image will not be shown. To do so, you
need to retrieve the image from the database which we are covering in the next page.

Example to retrieve image from Oracle database


By the help of PreparedStatement we can retrieve and store the image in the database.
The getBlob() method of PreparedStatement is used to get Binary information, it returns the
instance of Blob. After calling the getBytes() method on the blob object, we can get the array of
binary information that can be written into the image file.

Signature of getBlob() method of PreparedStatement

1. public Blob getBlob()throws SQLException

Signature of getBytes() method of Blob interface

1. public byte[] getBytes(long pos, int length)throws SQLException

We are assuming that image is stored in the imgtable.

1. CREATE TABLE "IMGTABLE"


2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /

Now let's write the code to retrieve the image from the database and write it into the directory so
that it can be displayed.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by
the img tag.

1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from imgtable");
11. ResultSet rs=ps.executeQuery();
12. if(rs.next()){//now on 1st row
13.
14. Blob b=rs.getBlob(2);//2 means 2nd column data
15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
16.
17. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
18. fout.write(barr);
19.
20. fout.close();
21. }//end of if
22. System.out.println("ok");
23.
24. con.close();
25. }catch (Exception e) {e.printStackTrace(); }
26. }
27. }

Now if you see the d drive, sonoo.jpg image is created.

Example to store file in Oracle database:


The setCharacterStream() method of PreparedStatement is used to set character information into
the parameterIndex.

Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws
SQLException
For storing file into the database, CLOB (Character Large Object) datatype is used in the table.
For example:

1. CREATE TABLE "FILETABLE"


2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /
1. import java.io.*;
2. import java.sql.*;
3.
4. public class StoreFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement(
12. "insert into filetable values(?,?)");
13.
14. File f=new File("d:\\myfile.txt");
15. FileReader fr=new FileReader(f);
16.
17. ps.setInt(1,101);
18. ps.setCharacterStream(2,fr,(int)f.length());
19. int i=ps.executeUpdate();
20. System.out.println(i+" records affected");
21.
22. con.close();
23.
24. }catch (Exception e) {e.printStackTrace();}
25. }
26. }

Example to retrieve file from Oracle database:


The getClob() method of PreparedStatement is used to get file information from the database.

Syntax of getClob method

1. public Clob getClob(int columnIndex){}


Let's see the table structure of this example to retrieve the file.

1. CREATE TABLE "FILETABLE"


2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /

The example to retrieve the file from the Oracle database is given below.

1. import java.io.*;
2. import java.sql.*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement("select * from filetable");
12. ResultSet rs=ps.executeQuery();
13. rs.next();//now on 1st row
14.
15. Clob c=rs.getClob(2);
16. Reader r=c.getCharacterStream();
17.
18. FileWriter fw=new FileWriter("d:\\retrivefile.txt");
19.
20. int i;
21. while((i=r.read())!=-1)
22. fw.write((char)i);
23.
24. fw.close();
25. con.close();
26.
27. System.out.println("success");
28. }catch (Exception e) {e.printStackTrace(); }
29. }
30. }

CallableStatement Interface
To call the stored procedures and functions, CallableStatement interface is used.
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.

What is the difference between stored procedures and functions.


The differences between stored procedures and functions are given below:
Stored Procedure Function
is used to perform business logic. is used to perform calculation.
must not have the return type. must have the return type.
may return 0 or more values. may return only one values.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output
Function supports only input parameter.
parameters.
Exception handling using try/catch block can be Exception handling using try/catch can't be
used in stored procedures. used in user defined functions.

How to get the instance of CallableStatement?


The prepareCall() method of Connection interface returns the instance of CallableStatement.
Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.

1. create or replace procedure "INSERTR"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /

The table structure is given below:

1. create table user420(id number(10), name varchar2(200));

In this example, we are going to call the stored procedure INSERTR that receives id and name as
the parameter and inserts it into the table user420. Note that you need to create the user420 table
as well to run this application.

1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10. stmt.setInt(1,1011);
11. stmt.setString(2,"Amit");
12. stmt.execute();
13.
14. System.out.println("success");
15. }
16. }

Now check the table in the database, value is inserted in the user420 table.

Example to call the function using JDBC


In this example, we are calling the sum4 function that receives two input and returns the sum of
the given number. Here, we have used the registerOutParameter method of CallableStatement
interface, that registers the output parameter with its corresponding type. It provides information
to the CallableStatement about the type of result being displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE,
BLOB, CLOB etc.
Let's create the simple function in the database first.

1. create or replace function sum4


2. (n1 in number,n2 in number)
3. return number
4. is
5. temp number(8);
6. begin
7. temp :=n1+n2;
8. return temp;
9. end;
10. /

Now, let's write the simple program to call the function.

1. import java.sql.*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
11. stmt.setInt(2,10);
12. stmt.setInt(3,43);
13. stmt.registerOutParameter(1,Types.INTEGER);
14. stmt.execute();
15.
16. System.out.println(stmt.getInt(1));
17.
18. }
19. }

Output: 53

Transaction Management in JDBC


Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
Advantage of Transaction Mangaement
fast performance It makes the performance fast because database is hit at the time of commit.

In JDBC, Connection interface provides methods to manage transaction.


Method Description
void setAutoCommit(boolean It is true bydefault means each transaction is committed
status) bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.

Simple example of transaction management in jdbc using Statement


Let's see the simple example of transaction management using Statement.

1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}

If you see the table emp400, you will see that 2 records has been added.

Example of transaction management in jdbc using PreparedStatement


Let's see the simple example of transaction management using PreparedStatement.

1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);
26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
39. }
40.
41.
42. System.out.println("Want to add more records y/n");
43. String ans=br.readLine();
44. if(ans.equals("n")){
45. break;
46. }
47.
48. }
49. con.commit();
50. System.out.println("record successfully saved");
51.
52. con.close();//before closing connection commit() is called
53. }catch(Exception e){System.out.println(e);}
54.
55. }}

It will ask to add more records until you press n. If you press n, transaction is committed.

Batch Processing in JDBC


Instead of executing a single query, we can execute a batch (group) of queries. It makes the
performance fast.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch
processing.

Advantage of Batch Processing


Fast Performance

Methods of Statement interface


The required methods for batch processing are given below:
Method Description
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

Example of batch processing in jdbc


Let's see the simple example of batch processing in jdbc. It follows following steps:
● Load the driver class
● Create Connection
● Create Statement
● Add query in the batch
● Execute Batch
● Close Connection
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
11.
12. stmt.executeBatch();//executing the batch
13.
14. con.commit();
15. con.close();
16. }}

If you see the table user420, two records has been added.

Example of batch processing using PreparedStatement

1. import java.sql.*;
2. import java.io.*;
3. class BP{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
11.
12. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
13. while(true){
14.
15. System.out.println("enter id");
16. String s1=br.readLine();
17. int id=Integer.parseInt(s1);
18.
19. System.out.println("enter name");
20. String name=br.readLine();
21.
22. System.out.println("enter salary");
23. String s3=br.readLine();
24. int salary=Integer.parseInt(s3);
25.
26. ps.setInt(1,id);
27. ps.setString(2,name);
28. ps.setInt(3,salary);
29.
30. ps.addBatch();
31. System.out.println("Want to add more records y/n");
32. String ans=br.readLine();
33. if(ans.equals("n")){
34. break;
35. }
36.
37. }
38. ps.executeBatch();
39.
40. System.out.println("record successfully saved");
41.
42. con.close();
43. }catch(Exception e){System.out.println(e);}
44.
45. }}

It will add the queries into the batch until user press n. Finally it executes the batch. Thus all the
added queries will be fired.

JDBC RowSet
The instance of RowSet is the java bean component because it has properties and java bean
notification mechanism. It is introduced since JDK 5.
It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to
use.
The implementation classes of RowSet interface are as follows:

● JdbcRowSet
● CachedRowSet
● WebRowSet
● JoinRowSet
● FilteredRowSet

Let's see how to create and execute RowSet.

1. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();


2. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
3. rowSet.setUsername("system");
4. rowSet.setPassword("oracle");
5.
6. rowSet.setCommand("select * from emp400");
7. rowSet.execute();

It is the new way to get the instance of JdbcRowSet since JDK 7.

Advantage of RowSet
The advantages of using RowSet are given below:

1. It is easy and flexible to use


2. It is Scrollable and Updatable bydefault

Simple example of JdbcRowSet


Let's see the simple example of JdbcRowSet without event handling code.

1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. while (rowSet.next()) {
24. // Generating cursor Moved event
25. System.out.println("Id: " + rowSet.getString(1));
26. System.out.println("Name: " + rowSet.getString(2));
27. System.out.println("Salary: " + rowSet.getString(3));
28. }
29.
30. }
31. }

The output is given below:


Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000

Full example of Jdbc RowSet with event handling


To perform event handling with JdbcRowSet, you need to add the instance of RowSetListener
in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be implemented. They are as follows:
1) public void cursorMoved(RowSetEvent event);
2) public void rowChanged(RowSetEvent event);
3) public void rowSetChanged(RowSetEvent event);
Let's write the code to retrieve the data and perform some additional tasks while cursor is moved,
cursor is changed or rowset is changed. The event handling operation can't be performed using
ResultSet so it is preferred now.

1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. //Adding Listener and moving RowSet
24. rowSet.addRowSetListener(new MyListener());
25.
26. while (rowSet.next()) {
27. // Generating cursor Moved event
28. System.out.println("Id: " + rowSet.getString(1));
29. System.out.println("Name: " + rowSet.getString(2));
30. System.out.println("Salary: " + rowSet.getString(3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. System.out.println("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. System.out.println("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. System.out.println("RowSet changed...");
45. }
46. }

The output is as follows:


Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...

Jdbc New Features


The latest version of JDBC is 4.0 currently. Java has updated jdbc api to ease and simplify the
coding to database interactivity.
Here, we are going to see the features included in Jdbc 3.0 and Jdbc 4.0.

Jdbc 3.0 Features


The important features of JDBC API 3.0 are as follows:

● Jdbc RowSet We have done the great discussion on JdbcRowSet in the previous page.
● Savepoint in transaction management Now you are able to create, rollback and release
the savepoint by Connection.setSavepoint(), Connection.rollback(Savepoint svpt) and
Connection.releaseSavepoint(Savepoint svpt) methods.
● Statement and ResultSet Caching for Connection Pooling Now you are able to reuse the
statement and result set because jdbc 3 provides you the facility of statement caching
and result set caching.
● Switching between Global and Local Transactions
● Retrieval of auto generated keys Now you are able to get the auto generated keys by
the method getGeneratedKeys().

Jdbc 4.0 Features


The important features of JDBC API 4.0 are given below:

● Automatic Loading of Driver class You don't need to write Class.forName() now because
it is loaded bydefault since jdbc4.
● Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class for
better readability and handling.
● New methods There are many new methods introduced in Connection,
PreparedStatement, CallableStatement, ResultSet etc.
● Improved DataSource Now data source implementation is improved.
● Event Handling support in Statement for Connection Pooling Now Connection Pooling
can listen statement error and statement closing events.

New Features in Java


There are many new features that have been added in java. There are major enhancement made
in Java5, Java6 and Java7 like auto-boxing, generics, var-args, java annotations, enum,
premain method etc.
Most of the interviewers ask questions from this chapter.

Do You Know ?
1. How to create generic class and generic method in java ?
2. What is annotation and how to create custom annotation ?
3. What is the advantage of assertion and where we should not use it ?
4. What is variable argument and what rules are defined for variable argument ?
5. What is the difference between import and static import ?
6. How autoboxing is applied in method overloading. Which concept beats autoboxing ?
7. What is enum type and how to specify specific value to the enum constants ?

J2SE 4 Features
The important feature of J2SE 4 is assertions. It is used for testing.

● Assertion (Java 4)

J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, var-
args, static import, for-each loop (enhanced for loop etc.

● For-each loop (Java 5)


● Varargs (Java 5)
● Static Import (Java 5)
● Autoboxing and Unboxing (Java 5)
● Enum (Java 5)
● Covariant Return Type (Java 5)
● Annotation (Java 5)
● Generics (Java 5)
JavaSE 6 Features
The important feature of JavaSE 6 is premain method (also known as instrumentation).

● Instrumentation (premain method) (Java 6)

JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.

● String in switch statement (Java 7)


● Binary Literals (Java 7)
● The try-with-resources (Java 7)
● Caching Multiple Exceptions by single catch (Java 7)
● Underscores in Numeric Literals (Java 7)

Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.

Advantage of Assertion:
It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:


There are two ways to use assertion. First way is:

1. assert expression;

and second way is:

1. assert expression1 : expression2;

Simple Example of Assertion in java:

1. import java.util.Scanner;
2.
3. class AssertionExample{
4. public static void main( String args[] ){
5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
15.
16.

If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:


There are some situations where assertion should be avoid to use. They are:

1. According to Sun Specification, assertion should not be used to check arguments in the
public methods because it should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.

For-each loop (Advanced or Enhanced For loop):


The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements.
The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code
more readable.

Advantage of for-each loop:

● It makes the code more readable.


● It elimnates the possibility of programming errors.
Syntax of for-each loop:

1. for(data_type variable : array | collection){}

Simple Example of for-each loop for traversing the array elements:

1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};
5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
12.

Output:12
13
14
44

Simple Example of for-each loop for traversing the collection elements:

1. import java.util.*;
2. class ForEachExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("vimal");
6. list.add("sonoo");
7. list.add("ratan");
8.
9. for(String s:list){
10. System.out.println(s);
11. }
12.
13. }
14. }
15.
Output:vimal
sonoo
ratan

Variable Argument (Varargs):


The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will have
to pass in the method, varargs is the better approach.

Advantage of Varargs:
We don't have to provide overloaded methods so less code.

Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

1. return_type method_name(data_type... variableName){}

Simple Example of Varargs in java:

1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }
7.
8. public static void main(String args[]){
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13. }
14.

Output:display method invoked


display method invoked
Another Program of Varargs in java:

1.
2. class VarargsExample2{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
18.

Output:display method invoked


display method invoked
hello
display method invoked
my
name
is
varargs

Rules for varargs:


While using the varargs, you must follow some rules otherwise program code won't compile.
The rules are as follows:

● There can be only one variable argument in the method.


● Variable argument (varargs) must be the last argument.

Examples of varargs that fails to compile:

1.
2. void method(String... a, int... b){}//Compile time error
3.
4. void method(int... a, String b){}//Compile time error
5.

Example of Varargs that is the last argument in the method:

1.
2. class VarargsExample3{
3.
4. static void display(int num, String... values){
5. System.out.println("number is "+num);
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16. }
17.

Output:number is 500
hello
number is 1000
my
name
is
varargs

Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of
a class directly. There is no need to qualify it by the class name.

Advantage of static import:

● Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:

● If you overuse the static import feature, it makes the program unreadable and
unmaintainable.
Simple Example of static import

1. import static java.lang.System.*;


2. class StaticImportExample{
3. public static void main(String args[]){
4.
5. out.println("Hello");//Now no need of System.out
6. out.println("Java");
7.
8. }
9. }
10.

Output:Hello
Java

What is the difference between import and static import?


The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a class
without the class qualification. The import provides accessibility to classes and interface whereas
static import provides accessibility to static members of the class.

Autoboxing and Unboxing:


The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding is required.

Simple Example of Autoboxing in java:

1.
2. class BoxingExample1{
3. public static void main(String args[]){
4. int a=50;
5. Integer a2=new Integer(a);//Boxing
6.
7. Integer a3=5;//Boxing
8.
9. System.out.println(a2+" "+a3);
10. }
11. }
12.

Output:50 5

Simple Example of Unboxing in java:


The automatic conversion of wrapper class type into corresponding primitive type, is known as
Unboxing. Let's see the example of unboxing:

1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
8. }
9. }
10.

Output:50

Autoboxing and Unboxing with comparison operators


Autoboxing can be performed with comparison operators. Let's see the example of boxing with
comparison operator:
1.
2. class UnboxingExample2{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Output:50

Autoboxing and Unboxing with method overloading


In method overloading, boxing and unboxing can be performed. There are some rules for
method overloading with boxing:

● Widening beats boxing


● Widening beats varargs
● Boxing beats varargs

1) Example of Autoboxing where widening beats boxing


If there is possibility of widening and boxing, widening beats boxing.
1.
2. class Boxing1{
3. static void m(int i){System.out.println("int");}
4. static void m(Integer i){System.out.println("Integer");}
5.
6. public static void main(String args[]){
7. short s=30;
8. m(s);
9. }
10. }
11.

Output:int

2) Example of Autoboxing where widening beats varargs


If there is possibility of widening and varargs, widening beats var-args.
1.
2. class Boxing2{
3. static void m(int i, int i2){System.out.println("int int");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. short s1=30,s2=40;
8. m(s1,s2);
9. }
10. }
11.
Output:int int

3) Example of Autoboxing where boxing beats varargs


Let's see the program where boxing beats variable argument:
1.
2. class Boxing3{
3. static void m(Integer i){System.out.println("Integer");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. int a=30;
8. m(a);
9. }
10. }
11.

Output:Integer

Method overloading with Widening and Boxing


Widening and Boxing can't be performed as given below:
1.
2. class Boxing4{
3. static void m(Long l){System.out.println("Long");}
4.
5. public static void main(String args[]){
6. int a=30;
7. m(a);
8. }
9. }
10.

Output:Compile Time Error

Java Enum
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.

Points to remember for Java Enum

● enum improves type safety


● enum can be easily used in switch
● enum can be traversed
● enum can have fields, constructors and methods
● enum may implement many interfaces but cannot extend any class because it internally
extends Enum class

Simple example of java enum

1. class EnumExample1{
2. public enum Season { WINTER, SPRING, SUMMER, FALL }
3.
4. public static void main(String[] args) {
5. for (Season s : Season.values())
6. System.out.println(s);
7.
8. }}

Output:WINTER
SPRING
SUMMER
FALL

What is the purpose of values() method in enum?


The java compiler internally adds the values() method when it creates an enum. The values()
method returns an array containing all the values of the enum.

Internal code generated by the compiler for the above example of enum type
The java compiler internally creates a static and final class that extends the Enum class as shown
in the below example:

1. public static final class EnumExample1$Season extends Enum


2. {
3. private EnumExample1$Season(String s, int i)
4. {
5. super(s, i);
6. }
7.
8. public static EnumExample1$Season[] values()
9. {
10. return (EnumExample1$Season[])$VALUES.clone();
11. }
12.
13. public static EnumExample1$Season valueOf(String s)
14. {
15. return (EnumExample1$Season)Enum.valueOf(EnumExample1$Season, s);
16. }
17.
18. public static final EnumExample1$Season WINTER;
19. public static final EnumExample1$Season SPRING;
20. public static final EnumExample1$Season SUMMER;
21. public static final EnumExample1$Season FALL;
22. private static final EnumExample1$Season $VALUES[];
23.
24. static
25. {
26. WINTER = new EnumExample1$Season("WINTER", 0);
27. SPRING = new EnumExample1$Season("SPRING", 1);
28. SUMMER = new EnumExample1$Season("SUMMER", 2);
29. FALL = new EnumExample1$Season("FALL", 3);
30. $VALUES = (new EnumExample1$Season[] {
31. WINTER, SPRING, SUMMER, FALL
32. });
33. }
34.
35. }

Defining Java enum


The enum can be defined within or outside the class because it is similar to a class.

Java enum example: defined outside class

1. enum Season { WINTER, SPRING, SUMMER, FALL }


2. class EnumExample2{
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }}
Output:WINTER

Java enum example: defined inside class

1. class EnumExample3{
2. enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
3. public static void main(String[] args) {
4. Season s=Season.WINTER;//enum type is required to access WINTER
5. System.out.println(s);
6. }}

Output:WINTER

Initializing specific values to the enum constants


The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize
the specific value to the enum constants by defining fields and constructors. As specified earlier,
Enum can have fields, constructors and methods.

Example of specifying initial value to the enum constants

1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4.
5. private int value;
6. private Season(int value){
7. this.value=value;
8. }
9. }
10. public static void main(String args[]){
11. for (Season s : Season.values())
12. System.out.println(s+" "+s.value);
13.
14. }}
15.

Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
Constructor of enum type is private. If you don't declare private compiler
internally creates private constructor.

1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }

Internal code generated by the compiler for the above example of enum type

1. final class Season extends Enum


2. {
3. public static Season[] values()
4. {
5. return (Season[])$VALUES.clone();
6. }
7. public static Season valueOf(String s)
8. {
9. return (Season)Enum.valueOf(Season, s);
10. }
11. private Season(String s, int i, int j)
12. {
13. super(s, i);
14. value = j;
15. }
16. public static final Season WINTER;
17. public static final Season SUMMER;
18. private int value;
19. private static final Season $VALUES[];
20. static
21. {
22. WINTER = new Season("WINTER", 0, 10);
23. SUMMER = new Season("SUMMER", 1, 20);
24. $VALUES = (new Season[] {
25. WINTER, SUMMER
26. });
27. }
28. }
Can we create the instance of enum by new keyword?
No, because it contains private constructors only.

Can we have abstract method in enum?


Yes, ofcourse! we can have abstract methods and can provide the implementation of these
methods.

Java enum in switch statement


We can apply enum on switch statement as in the given example:

Example of applying enum on switch statement

1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

3. public static void main(String args[]){


4. Day day=Day.MONDAY;
5.
6. switch(day){
7. case SUNDAY:
8. System.out.println("sunday");
9. break;
10. case MONDAY:
11. System.out.println("monday");
12. break;
13. default:
14. System.out.println("other day");
15. }
16. }}

Output:monday

Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods
or fields to indicate some additional information which can be used by java compiler and JVM.
Annotations in java are used to provide additional information, so it is an alternative option for
XML and java marker interfaces.
First, we will learn some built-in annotations then we will move on creating and using custom
annotations.
Built-In Java Annotations
There are several built-in annotations in java. Some annotations are applied to java code and
some to other annotations.

Built-In Java Annotations used in java code

● @Override
● @SuppressWarnings
● @Deprecated

Built-In Java Annotations used in other annotations

● @Target
● @Retention
● @Inherited
● @Documented

Understanding Built-In Annotations in java


Let's understand the built-in annotations first.

@Override
@Override annotation assures that the subclass method is overriding the parent class method. If
it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){System.out.println("eating foods");}//should be eatSomething
8. }
9.
10. class TestAnnotation1{
11. public static void main(String args[]){
12. Animal a=new Dog();
13. a.eatSomething();
14. }}

Output:Comple Time Error

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

1. import java.util.*;
2. class TestAnnotation2{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5. ArrayList list=new ArrayList();
6. list.add("sonoo");
7. list.add("vimal");
8. list.add("ratan");
9.
10. for(Object obj:list)
11. System.out.println(obj);
12.
13. }}

Now no warning at compile time.


If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at
compile time because we are using non-generic collection.

@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.

1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
7.
8. class TestAnnotation3{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}

At Compile Time:
Note: Test.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

At Runtime:
hello n

Custom Annotation
To create and use custom java annotation, visit the next page.

Java Custom Annotation


Java Custom annotations or Java User-defined annotations are easy to create and use. The
@interface element is used to declare an annotation. For example:

1. @interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature


There are few points that should be remembered by the programmer.

1. Method should not have any throws clauses


2. Method should return one of the following: primitive data types, String, Class, enum or
array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

Types of Annotation
There are three types of annotations.

1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:

1. @interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:

1. @interface MyAnnotation{
2. int value();
3. }

We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value() default 0;
3. }

How to apply Single-Value Annotation


Let's see the code to apply the single value annotation.

1. @MyAnnotation(value=10)

The value can be anything.

3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:

1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }

We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }

How to apply Multi-Value Annotation


Let's see the code to apply the multi-value annotation.

1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations used in custom annotations in java

● @Target
● @Retention
● @Inherited
● @Documented

@Target
@Target tag is used to specify at which type, the annotation is used.
The java.lang.annotation.ElementType enum declares many constants to specify the type of
element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:
Element Types Where the annotation can be applied
TYPE class, interface or enumeration
FIELD fields
METHOD methods
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation type
PARAMETER parameter

Example to specify annoation for a class

1. @Target(ElementType.TYPE)
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }
Example to specify annoation for a class, methods or fields

1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

@Retention
@Retention annotation is used to specify to what level annotation will be available.
RetentionPolicy Availability
refers to the source code, discarded during compilation. It will not be
RetentionPolicy.SOURCE
available in the compiled class.
refers to the .class file, available to java compiler but not to JVM . It is
RetentionPolicy.CLASS
included in the class file.
RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .

Example to specify the RetentionPolicy

1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }

Example of custom annotation: creating, applying and accessing


annotation
Let's see the simple example of creating, applying and accessing annotation.
File: Test.java

1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11. //Applying annotation
12. class Hello{
13. @MyAnnotation(value=10)
14. public void sayHello(){System.out.println("hello annotation");}
15. }
16.
17. //Accessing annotation
18. class TestCustomAnnotation1{
19. public static void main(String args[])throws Exception{
20.
21. Hello h=new Hello();
22. Method m=h.getClass().getMethod("sayHello");
23.
24. MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
25. System.out.println("value is: "+manno.value());
26. }}

Output:value is: 10

How built-in annotaions are used in real scenario?


In real scenario, java programmer only need to apply annotation. He/She doesn't need to create
and access annotation. Creating and Accessing annotation is performed by the implementation
provider. On behalf of the annotation, java compiler or JVM performs some additional
operations.

@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.

1. @Inherited
2. @interface ForEveryone { }//Now it will be available to subclass also
3.
4. @interface ForEveryone { }
5. class Superclass{}
6.
7. class Subclass extends Superclass{}

@Documented
The @Documented Marks the annotation for inclusion in the documentation.

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics,
forces the java programmer to store specific type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:
1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store
other objects.
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.

1. List list = new ArrayList();


2. list.add("hello");
3. String s = (String) list.get(0);//typecasting

After Generics, we don't need to typecast the object.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. list.add(32);//Compile Time Error

Syntax to use generic collection

1. ClassOrInterface<Type>
Example to use Generics in java

1. ArrayList<String>

Full Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Output:element is: jai


rahul
jai

Example of Java Generics using Map


Now we are going to use map elements using generics. Here, we need to pass key and value. Let
us understand it by a simple example:

1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}

Output:1 vijay
2 ankit
4 umesh

Generic class
A class that can refer to any type is known as generic class. Here, we are using T type parameter
to create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
Creating generic class:

1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type
you specify for the class, will be used to store and retrieve the data.
Using generic class:
Let’s see the code to use the generic class.

1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2

Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:

1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value

Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using here E
to denote the element.

1. public class TestGenerics4{


2.
3. public static < E > void printArray(E[] elements) {
4. for ( E element : elements){
5. System.out.println(element );
6. }
7. System.out.println();
8. }
9. public static void main( String args[] ) {
10. Integer[] intArray = { 10, 20, 30, 40, 50 };
11. Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
12.
13. System.out.println( "Printing Integer Array" );
14. printArray( intArray );
15.
16. System.out.println( "Printing Character Array" );
17. printArray( charArray );
18. }
19. }

Output:Printing Integer Array


10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T

Wildcard in Java Generics


The ? (question mark) symbol represents wildcard element. It means any type. If we write <?
extends Number>, it means any child class of Number e.g. Integer, Float, double etc. Now we
can call the method of Number class through any child class object.
Let's understand it by the example given below:

1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11.
12.
13. class GenericTest{
14. //creating a method that accepts only child class of Shape
15. public static void drawShapes(List<? extends Shape> lists){
16. for(Shape s:lists){
17. s.draw();//calling method of Shape class by child class instance
18. }
19. }
20. public static void main(String args[]){
21. List<Rectangle> list1=new ArrayList<Rectangle>();
22. list1.add(new Rectangle());
23.
24. List<Circle> list2=new ArrayList<Circle>();
25. list2.add(new Circle());
26. list2.add(new Circle());
27.
28. drawShapes(list1);
29. drawShapes(list2);
30. }}

drawing rectangle
drawing circle
drawing circle

RMI (Remote Method Invocation)


1. Remote Method Invocation (RMI)
2. Understanding stub and skeleton
1. stub
2. skeleton
3. Requirements for the distributed applications
4. Steps to write the RMI program
5. RMI Example

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
The RMI provides remote communication between the applications using two objects stub and
skeleton.

Understanding stub and skeleton


RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's understand
the stub and skeleton objects:

stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.

Understanding requirements for the distributed applications


If any application performs these tasks, it can be distributed application.
.

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

Steps to write the RMI program


The is given the 6 steps to write the RMI program.
1. Create the remote interface
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the
rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application,
both client and server interacts with the remote interface. The client application invokes methods
on the proxy object, RMI sends the request to the remote JVM. The return value is sent back to
the proxy object and then to the client application.

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that
extends the Remote interface. There is only one method named add() and it declares
RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing the implementation of
the Remote interface, we need to

● Either extend the UnicastRemoteObject class,


● or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.

1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.

1. rmic AdderRemote

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't specify the port number,
it uses a default port number. In this example, we are using the port number 5000.

1. rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object. The Naming class provides 5 methods.

1. public static java.rmi.Remote lookup(java.lang.String) throws


java.rmi.NotBoundException, java.net.MalformedURLException,
java.rmi.RemoteException; it returns the reference of the remote object.
2. public static void bind(java.lang.String, java.rmi.Remote) throws
java.rmi.AlreadyBoundException, java.net.MalformedURLException,
java.rmi.RemoteException; it binds the remote object with the given name.
3. public static void unbind(java.lang.String) throws java.rmi.RemoteException,
java.rmi.NotBoundException, java.net.MalformedURLException; it destroys the
remote object which is bound with the given name.
4. public static void rebind(java.lang.String, java.rmi.Remote) throws
java.rmi.RemoteException, java.net.MalformedURLException; it binds the remote
object to the new name.
5. public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException,
java.net.MalformedURLException; it returns an array of the names of the remote
objects bound in the registry.

In this example, we are binding the remote object by the name sonoo.

1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the remote
object from another machine, change the localhost to the host name (or IP address) where the
remote object is located.

1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }

1. For running this rmi example,


2.
3. 1) compile all the java files
4.
5. javac *.java
6.
7. 2)create stub and skeleton object by rmic tool
8.
9. rmic AdderRemote
10.
11. 3)start rmi registry in one command prompt
12.
13. rmiregistry 5000
14.
15. 4)start the server in another command prompt
16.
17. java MyServer
18.
19. 5)start the client application in another command prompt
20.
21. java MyClient
Output of this RMI example
Meaningful example of RMI application with database
Consider a scenario, there are two applications running in different machines. Let's say
MachineA and MachineB, machineA is located in United States and MachineB in India.
MachineB want to get list of all the customers of MachineA application.
Let's develop the RMI application by following the steps.

1) Create the table


First of all, we need to create the table in the database. Here, we are using Oracle10 database.
2) Create Customer class and Remote interface
File: Customer.java

1. package com.java;
2. public class Customer implements java.io.Serializable{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }

Note: Customer class must be Serializable.


File: Bank.java

1. package com.java;
2. import java.rmi.*;
3. import java.util.*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }

3) Create the class that provides the implementation of Remote interface


File: BankImpl.java

1. package com.java;
2. import java.rmi.*;
3. import java.rmi.server.*;
4. import java.sql.*;
5. import java.util.*;
6. class BankImpl extends UnicastRemoteObject implements Bank{
7. BankImpl()throws RemoteException{}
8.
9. public List<Customer> getCustomers(){
10. List<Customer> list=new ArrayList<Customer>();
11. try{
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
14. PreparedStatement ps=con.prepareStatement("select * from customer400");
15. ResultSet rs=ps.executeQuery();
16.
17. while(rs.next()){
18. Customer c=new Customer();
19. c.setAcc_no(rs.getInt(1));
20. c.setFirstname(rs.getString(2));
21. c.setLastname(rs.getString(3));
22. c.setEmail(rs.getString(4));
23. c.setAmount(rs.getFloat(5));
24. list.add(c);
25. }
26.
27. con.close();
28. }catch(Exception e){System.out.println(e);}
29. return list;
30. }//end of getCustomers()
31. }

4) Compile the class rmic tool and start the registry service by rmiregistry tool

5) Create and run the Server


File: MyServer.java

1. package com.java;
2. import java.rmi.*;
3. public class MyServer{
4. public static void main(String args[])throws Exception{
5. Remote r=new BankImpl();
6. Naming.rebind("rmi://localhost:6666/java",r);
7. }}

6) Create and run the Client


File: MyClient.java

1. package com.java;
2. import java.util.*;
3. import java.rmi.*;
4. public class MyClient{
5. public static void main(String args[])throws Exception{
6. Bank b=(Bank)Naming.lookup("rmi://localhost:6666/java");
7.
8. List<Customer> list=b.getCustomers();
9. for(Customer c:list){
10. System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()
11. +" "+c.getEmail()+" "+c.getAmount());
12. }
13.
14. }}
Internationalization and Localization in Java
1. Internationalization and Localization
2. Understanding the culturally dependent data
3. Locale class
4. Example of Local class that prints the informations of the default locale
5. Example of Local class that prints english in different languages
6. Example of Local class that print display language of many locales

Internationalization is also abbreviated as I18N because there are total 18 characters between
the first letter 'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be adapted to different
languages and regions.
Internationalization is one of the powerful concept of java if you are developing an application
and want to display messages, currencies, date, time etc. according to the specific region or
language.
Localization is also abbreviated as I10N because there are total 10 characters between the first
letter 'L' and last letter 'N'. Localization is the mechanism to create such an application that can
be adapted to a specific language and region by adding locale-specific text and component.

Do You Know ?

● What is the use of Locale class ?


● How can we globalize the messages (or) What is the use of ResourceBundle class?
● How can we internationalize the date, time, number, currency and measurements?
Understanding the culturally dependent data before starting
internationalization
Before starting the internationalization, Let's first understand what are the informations that
differ from one region to another. There is the list of culturally dependent data:

● Messages
● Dates
● Times
● Numbers
● Currencies
● Measurements
● Phone Numbers
● Postal Addresses
● Labels on GUI components etc.

Importance of Locale class in Internationalization


An object of Locale class represents a geographical or cultural region. This object can be used to
get the locale specific information such as country name, language, variant etc.

Fields of Locale class


There are fields of Locale class:

1. public static final Locale ENGLISH


2. public static final Locale FRENCH
3. public static final Locale GERMAN
4. public static final Locale ITALIAN
5. public static final Locale JAPANESE
6. public static final Locale KOREAN
7. public static final Locale CHINESE
8. public static final Locale SIMPLIFIED_CHINESE
9. public static final Locale TRADITIONAL_CHINESE
10. public static final Locale FRANCE
11. public static final Locale GERMANY
12. public static final Locale ITALY
13. public static final Locale JAPAN
14. public static final Locale KOREA
15. public static final Locale CHINA
16. public static final Locale PRC
17. public static final Locale TAIWAN
18. public static final Locale UK
19. public static final Locale US
20. public static final Locale CANADA
21. public static final Locale CANADA_FRENCH
22. public static final Locale ROOT

Constructors of Locale class


There are three constructors of Locale class.They are as follows:

1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)

Commonly used methods of Locale class


There are given commonly used methods of Locale class.

1. public static Locale getDefault() it returns the instance of current Locale


2. public static Locale[] getAvailableLocales() it returns an array of available locales.
3. public String getDisplayCountry() it returns the country name of this locale object.
4. public String getDisplayLanguage() it returns the language name of this locale object.
5. public String getDisplayVariant() it returns the variant code for this locale object.
6. public String getISO3Country() it returns the three letter abbreviation for the current
locale's country.
7. public String getISO3Language() it returns the three letter abbreviation for the current
locale's language.

Example of Local class that prints the informations of the default locale
In this example, we are displaying the informations of the default locale. If you want to get the
informations about any specific locale, comment the first line statement and uncomment the
second line statement in the main method.

1. import java.util.*;
2. public class LocaleExample {
3. public static void main(String[] args) {
4. Locale locale=Locale.getDefault();
5. //Locale locale=new Locale("fr","fr");//for the specific locale
6.
7. System.out.println(locale.getDisplayCountry());
8. System.out.println(locale.getDisplayLanguage());
9. System.out.println(locale.getDisplayName());
10. System.out.println(locale.getISO3Country());
11. System.out.println(locale.getISO3Language());
12. System.out.println(locale.getLanguage());
13. System.out.println(locale.getCountry());
14.
15. }
16. }

Output:United States
English
English (United States)
USA
eng
en
US

Example of Local class that prints english in different languages


In this example, we are displaying english language in different language. Let's see how english
is written in french and spanish languages.

1. import java.util.*;
2. public class LocaleExample2 {
3. public static void main(String[] args) {
4. Locale enLocale = new Locale("en", "US");
5. Locale frLocale = new Locale("fr", "FR");
6. Locale esLocale = new Locale("es", "ES");
7. System.out.println("English language name (default): " +
8. enLocale.getDisplayLanguage());
9.
10. System.out.println("English language name in French: " +
11. enLocale.getDisplayLanguage(frLocale));
12. System.out.println("English language name in spanish: " +
13. enLocale.getDisplayLanguage(esLocale));
14. }
15.
16. }

Example of Local class that print display language of many locales


In this example, we are displaying the display lanuage of many locales.
1. import java.util.*;
2. public class LocaleEx {
3. public static void main(String[] args) {
4. Locale[] locales = { new Locale("en", "US"),
5. new Locale("es", "ES"), new Locale("it", "IT") };
6.
7. for (int i=0; i< locales.length; i++) {
8. String displayLanguage = locales[i].getDisplayLanguage(locales[i]);
9. System.out.println(locales[i].toString() + ": " + displayLanguage);
10. }
11. }
12.
13. }

Output:en_US: English
es_ES: espa?ol
it_IT: italiano

What we will learn in Internationalization Tutorial ?


● ResourceBundle class
● I18N with Date
● I18N with Time
● I18N with Number
● I18N with Currency
● I18N with Measurements

ResourceBundle class in Java


1. ResourceBundle class
2. Commonly used methods of ResourceBundle class
3. Example of ResourceBundle class

The ResourceBundle class is used to internationalize the messages. In other words, we can say
that it provides a mechanism to globalize the messages.
The hardcoded message is not considered good in terms of programming, because it differs from
one country to another. So we use the ResourceBundle class to globalize the massages. The
ResourceBundle class loads these informations from the properties file that contains the
messages.
Conventionally, the name of the properties file should be filename_languagecode_country code
for example MyMessage_en_US.properties.
Commonly used methods of ResourceBundle class
There are many methods in the ResourceBundle class. Let's see the commonly used methods of
the ResourceBundle class.

● public static ResourceBundle getBundle(String basename) returns the instance of the


ResourceBundle class for the default locale.
● public static ResourceBundle getBundle(String basename, Locale locale) returns the
instance of the ResourceBundle class for the specified locale.
● public String getString(String key) returns the value for the corresponding key from this
resource bundle.

Example of ResourceBundle class


Let's see the simple example of ResourceBundle class. In this example, we are creating three
files:

● MessageBundle_en_US.properties file contains the localize message for US country.


● MessageBundle_in_ID.properties file contains the localize message for Indonaisa
country.
● InternationalizationDemo.java file that loads these properties file in a bundle and prints
the messages.

MessageBundle_en_US.properties

MessageBundle_in_ID.properties

InternationalizationDemo.java

1. import java.util.Locale;
2. import java.util.ResourceBundle;
3. public class InternationalizationDemo {
4. public static void main(String[] args) {
5.
6. ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.US);
7. System.out.println("Message in "+Locale.US +":"+bundle.getString("greeting"));
8.
9. //changing the default locale to indonasian
10. Locale.setDefault(new Locale("in", "ID"));
11. bundle = ResourceBundle.getBundle("MessageBundle");
12. System.out.println("Message in "+Locale.getDefault()+":"+bundle.getString("greeting")
);
13.
14. }
15. }

Output:Message in en_US : Hello, how r u?


Message in in_ID : halo, apa kabar?

Internationalizing Date (I18N with Date)


1. Internationalizing Date
2. Commonly used methods of the DateFormat class
3. Example of Inernationalizing Date

The format of the dates differ from one region to another that is why we internationalize the
dates.
We can internationalize the date by using the getDateInstance() method of the DateFormat
class. It receives the locale object as a parameter and returns the instance of the DateFormat
class.

Commonly used methods of DateFormat class for internationalizing date


There are many methods of the DateFormat class. Let's see the two methods of the DateFormat
class for internationalizing the dates.

● public static DateFormat getDateInstance(int style, Locale locale) returns the instance
of the DateFormat class for the specified style and locale. The style can be DEFAULT,
SHORT, LONG etc.
● public String format(Date date) returns the formatted and localized date as a string.

Example of Internationalizing Date


In this example, we are displaying the date according to the different locale such as UK, US,
FRANCE etc. For this purpose we have created the printDate() method that receives Locale
object as an instance. The format() method of the DateFormat class receives the Date object and
returns the formatted and localized date as a string.
1. import java.text.DateFormat;
2. import java.util.*;
3. public class InternationalizationDate {
4.
5. static void printDate(Locale locale){
6. DateFormat formatter=DateFormat.getDateInstance(DateFormat.DEFAULT,locale);
7. Date currentDate=new Date();
8. String date=formatter.format(currentDate);
9. System.out.println(date+" "+locale);
10. }
11.
12. public static void main(String[] args) {
13. printDate(Locale.UK);
14. printDate(Locale.US);
15. printDate(Locale.FRANCE);
16. }
17. }

Output:01-Mar-2012 en_GB
Mar 1, 2012 en_US
1 mars 2012 fr_FR

Internationalizing Time (I18N with Time)


1. Internationalizing Time
2. Example of Internationalizing Time

The display format of the time differs from one region to another, so we need to internationalize
the time.
For internationalizing the time, the DateFormat class provides some useful methods.
The getTimeInstance() method of the DateFormat class returns the instance of the DateFormat
class for the specified style and locale.
Syntax of the getTimeInstance() method is given below:
Example of Internationalizing Time
In this example, we are displaying the current time for the specified locale. The format() method
of the DateFormat class receives date object and returns the formatted and localized time as a
string. Notice that the object of Date class prints date and time both.

1. import java.text.DateFormat;
2. import java.util.*;
3.
4. public class InternationalizingTime {
5.
6. static void printTime(Locale locale){
7. DateFormat formatter=DateFormat.getTimeInstance(DateFormat.DEFAULT,locale);
8. Date currentDate=new Date();
9. String time=formatter.format(currentDate);
10. System.out.println(time+" in locale "+locale);
11. }
12.
13. public static void main(String[] args) {
14. printTime(Locale.UK);
15. printTime(Locale.US);
16. printTime(Locale.FRANCE);
17. }
18. }

Output:16:22:49 in locale en_GB


4:22:49 PM in locale en_US
16:22:49 in locale fr_FR

Internationalizing Number (I18N with Number)


1. Internationalizing Number
2. Example of Internationalizing Number

The representation of the numbers differ from one locale to another. Internationalizing the
numbers is good approach for the application that displays the informations according to the
locales.
The NumberFormat class is used to format the number according to the specific locale. To get
the instance of the NumberFormat class, we need to call either getInstance() or
getNumberInstance() methods.
Syntax of these methods is given below:

1. public static NumberFormat getNumberInstance(Locale locale)


2. public static NumberFormat getInstance(Locale locale)//same as above
3. </textareaa></div>
4.
5. <hr/>
6. <a id="numberex"></a>
7. <h3 class="h3ex">Example of Internationalizing Number</h3>
8. <p>In this example, we are internationalizing the number. The format method of the Nu
mberFormat class formats the double value into the locale specific number.
9. </p>
10.
11. <div class="codeblock"><textarea name="code" class="java">
12.
13. import java.text.NumberFormat;
14. import java.util.*;
15.
16. public class InternalizationNumber {
17.
18. static void printNumber(Locale locale){
19. double dbl=105000.3245;
20. NumberFormat formatter=NumberFormat.getNumberInstance(locale);
21. String number=formatter.format(dbl);
22. System.out.println(number+" for the locale "+locale);
23. }
24.
25. public static void main(String[] args) {
26. printNumber(Locale.UK);
27. printNumber(Locale.US);
28. printNumber(Locale.FRANCE);
29. printNumber(Locale.JAPAN);
30.
31. }
32. }

Output:105,500.324 for the locale en_GB


105,000.324 for the locale en_US
105,a000,324 for the locale fr_FR
105,000.324 for the locale ja_JP

Internationalizing Currency (I18N with Currency)


1. Internationalizing Currency
2. Example of Internationalizing Currency
As we have internationalize the date, time and numbers, we can internationalize the currency
also. The currency differs from one country to another so we need to internationalize the
currency.
The NumberFormat class provides methods to format the currency according to the locale. The
getCurrencyInstance() method of the NumberFormat class returns the instance of the
NumberFormat class.
The syntax of the getCurrencyInstance() method is given below:

1. public static NumberFormat getCurrencyInstance(Locale locale)


2. </pre></div>
3. <a id="currencyex"></a>
4. <h3 class="h3ex">Example of Internationalizing Currency</h3>
5. <p>In this example, we are internationalizing the currency. The format method of the N
umberFormat class formats the double value into the locale specific currency.
6. </p>
7.
8. <div class="codeblock"><textarea name="code" class="java">
9. import java.text.NumberFormat;
10. import java.util.*;
11. public class InternalizationCurrency {
12.
13. static void printCurrency(Locale locale){
14. double dbl=10500.3245;
15. NumberFormat formatter=NumberFormat.getCurrencyInstance(locale);
16. String currency=formatter.format(dbl);
17. System.out.println(currency+" for the locale "+locale);
18. }
19.
20. public static void main(String[] args) {
21. printCurrency(Locale.UK);
22. printCurrency(Locale.US);
23. printCurrency(Locale.FRANCE);
24. }
25. }

Output:?10,500.32 for the locale en_GB


$10,500.32 for the locale en_US
10 500,32 ? for the locale fr_FR

You might also like