0% found this document useful (0 votes)
2 views

Java Notes (1)

The document discusses Object-Oriented Programming (OOP) as a methodology that organizes complex programs through concepts like inheritance, encapsulation, and polymorphism, evolving from earlier programming paradigms. It also outlines the history of Java, its development by the Green Team, and its features such as simplicity, robustness, and portability. Additionally, it provides a brief guide on creating a simple Java program and highlights the key features that contribute to Java's popularity.

Uploaded by

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

Java Notes (1)

The document discusses Object-Oriented Programming (OOP) as a methodology that organizes complex programs through concepts like inheritance, encapsulation, and polymorphism, evolving from earlier programming paradigms. It also outlines the history of Java, its development by the Green Team, and its features such as simplicity, robustness, and portability. Additionally, it provides a brief guide on creating a simple Java program and highlights the key features that contribute to Java's popularity.

Uploaded by

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

UINT I

Object-Oriented Thinking

Object Oriented Thinking


When computers were first invented, programming was done manually by toggling in a
binary machine instructions by use of front panel.
As programs began to grow, high level languages were introduced that gives the
programmer more tools to handle complexity.
The first widespread high level language is FORTRAN. Which gave birth to structured
programming in 1960’s. The Main problem with the high level language was they have no
specific structure and programs becomes larger, the problem of complexity also increases.
So C became the popular structured oriented language to solve all the above problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a
new way of programming was invented and it was OOP. OOP is a programming
methodology that helps to organize complex programs through the use of inheritance,
encapsulation & polymorphism.
OOP is a Revolutionary idea totally unlike anything that has came before in programming
OOP is an evolutionary step following naturally on the heels of earlier programming
abstractions.
A way of viewing world:
It means how we handle the real world situations through OOP and how we could make the
computer closely model the techniques.
Eg: Raju wished to send some flowers to his friend for his birthday & he was living some
miles away. He went to local florist and said the kind of flowers. He want to send to his
friend’s address. And florist assured those flowers will be sent automatically.
Agents:
The Structure of OOP is similar to that of a community, that consists of agents interacting
with each other. These agents are also called as objects. An agent or an object plays a role of
providing a service or performing an action, and other members of this community can
access these services or actions.
Consider an eg, raju and ravi are good friends who live in two different cities far from each
other. If Raju wants to send flowers to ravi, he can request his local florist ‘hari’ to send
flowers to ravi by giving all the information along with the address.
Hari works as an agent (or object) who performs the task of satisfying raju’s request. Hari
then performs a set of operations or methods to satisfy the request which is actually hidden
from ravi, Hari forwards a message to ravi’s local florist. Then local florist asks a delivery
person to deliver those flowers to ravi. The objects or agents helping raju in solving the
problem of sending flowers to his friend ravi can be shown in figure.

1
Responsibilities:
A fundamental concept in OOP is to describe behavior in terms of responsibilities. A
Request to perform an action denotes the desired result. An object can use any technique
that helps in obtaining the desired result and this process will not have any interference
from other object. The abstraction level will be increased when a problem is evaluated in
terms of responsibilities. The objects will thus become independent from each other which
will help in solving complex problems. An Object has a collection of responsibilities related
with it which is termed as ‘protocol’
The Operation of a traditional program depends on how it acts on data structures. Where
as an OOP operates by requesting data structure to perform a service.
Messages & Methods:
When a message is passed to an agent (or object) that is capable of performing an action,
then that action will be initiated in OOP. An object which receives the message sent is called
‘receiver’. When a receiver accepts a message, it means that the receiver has accepted the
responsibility of processing the requested action. It then performs a method as a response
to the message in order to fulfill the request.
A Receiver’s class determines which method is to be invoked by the object in response to a
message. When similar messages are requested then all the objects of a class will invoke
the same method.
All objects are said to be the instances of a class.
For e.g., If ‘flower’ is a class then Rose is its instance
Class Hierarchies (Inheritance):
It is possible to organize classes in the form of a structure that corresponds to hierarchical
inheritance. All the child classes can inherit the properties of their parent classes. A parent
class that does not have any direct instances is called an abstract class. It is used in the
creation of subclasses.

2
Object Oriented Thinking
Let ‘Hari’ be a florist, but florist more specific form of shot keeper. Additionally, a shop
keeper is a human and a human is definitely a mammal. But a mammal is an animal &
animal is material object.
All these categories along with their relationships can be represented using a graphical
technique shown in figure. Each category is regarded as a class. The classes at the top of the
tree are said to be more abstract classes and the classes at the bottom of the tree are said to
be more specific classes.
Inheritance is a principle, according to which knowledge of a category (or class) which is
more general can also be applied to a category which is more specific.
Method Binding:
When the method is super class have same name that of the method in sub class, then the
subclass method overridden the super-class method. The program will find out a class to
which the reference is actually pointing and that class method will be binded.
E.g.
class parent
{ void print()
{ System.out.println(“From Parent”);
}
}
class child extends parent
{
void print()
{ System.out.println(“From Child”);
}
}
class Bind
{
Public static void main(String arg[])
{ child ob=new child();
ob.print();

3
}
}
o/p: From Child
The child’s object ‘ob’ will point to child class print() method thus that method will be
binded.
Overriding:
When the name and type of the method in a subclass is same as that of a method in its
super class. Then it is said that the method present in subclass overrides the method
present in super class. Calling an overridden method from a subclass will always point to
the type of that method as defined by the subclass, where as the type of method defined by
super class is hidden.
E.g. (above ’method binding’ example)
Exceptions:
Exception is a error condition that occurs in the program execution. There is an object
called ‘Exception’ object that holds error information. This information includes the type
and state of the program when the error occurred.
E.g. Stack overflow, Memory error etc
Summary of OOP concepts (proposed by Alan kay):
• Everything is an
• Computation is performed by objects communicating with each other, requesting
that other objects perform actions. Objects communicate by sending &
receiving messages. A message is a request for an action bundled with whatever
arguments may be necessary to complete the task.
• Each object has its own memory, which consists of other objects.
• Every Object is an instance of class. A class simply represents a grouping of similar
objects, such as integers or lists.
• The class is the repository for behavior associated with an object. That is all objects
that are instances of same class can perform the same actions.
• Classes are organized into a singly rooted tree structure, called inheritance
hierarchy.
Copyng with complexity:
When programs are larger then complex is more programmers found it difficult to
remember all the information they needed to know in order to develop or debug their
software.
Non-Linear behavior of complexity:
When projects become larger, a task that can be solved by a programmer in 2 months
can’t be accomplished by 2 programmers working for one month. The reason for this non-
linear behavior is complexity. The inter connections between the software components is
complicated. The OOP designers illustrated this with a memorable phrase “The bearing of a
child takes nine months, no matter how many women are assigned to the task”
Abstraction Mechanisms:

4
In general to reduce the complexities in OOP we use abstraction mechanism. Abstraction is
the ability to encapsulate, isolate design and execution the information. Object oriented
techniques can be seen as a natural outcome of a long historical progression from
procedures, to modules, to abstract datatypes and finally to objects.
Procedures are the functions that allowed tasks to be executed repeatedly. The procedure
gave the first possibility for information hiding.
Modules are the independent parts of program. A module provides the ability to divide the
program into two parts. The public part is accessible outside the module. The private part
is accessible only with in the module.
An abstract data type is a programmer defined datatype that can be manipulated like the
system defined datatypes. Objects are instances of a class. Object oriented programming
adds several important new ideas. Among them, message passing, inheritance and
polymorphism are important. Message passing is the idea that the interpretation of a
message can vary with different objects. Inheritance allows different datatypes to share
same code, and increase the functionality. Polymorphism allows this shared code to be
tailored to fit t he specific circumstances of individual datatypes.

History of Java
• History of Java
• Java Version History
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the
time. The history of Java starts with the Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such as set-
top boxes, televisions, etc. However, it was suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members started the project in
the early '90s.

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


solutions, etc. There are given significant points that describe 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) Initially designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java named "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.

5
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java Programming named "Java"?
7) Why had they chosen 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 than other names.
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having coffee near
his office.
9) Notice that Java is just a name, not an acronym.
10) Initially 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). After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds the new features in Java.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE
10.
• 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 Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
First Java Program | Hello World Example
• Software Requirements
• Creating Hello Java Example
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 the main method.
Let's understand the requirement first.
The requirement for Java Hello World 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. http://www.javatpoint.com/how-to-set-path-
6
in-java
• Create the java program
• Compile and run the java program

Creating Hello World 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
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code
into byte code.
Parameters used in 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 the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main method is executed by the JVM, so it
doesn't require to create an 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 the starting point of the program.
• String[] args is used for command line argument. We will learn it later.
• System.out.println() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class. We will
learn about the internal working of System.out.println statement later.

Features of Java(Java buzz words):


The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of
Java are also known as java buzzwords.
A list of most important features of Java language is given below.

• Simple
• Object-Oriented
• Portable

7
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Robust
Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Distributed
• Java is designed for distributed environment of the Internet. Its used for creating
applications on networks.
• Java applications can access remote objects on Internet as easily as they can do in local
system.
• Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Compiled and Interpreted
• Usually a computer language is either compiled or Interpreted. Java combines both this
approach and makes it a two-stage system.
• Compiled : Java enables creation of a cross platform programs by compiling into an
intermediate representation called Java Bytecode.
• Interpreted : Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
Robust
• It provides many features that make the program execute reliably in variety of
environments.
• Java is a strictly typed language. It checks code both at compile time and runtime.
• Java takes care of all memory management problems with garbage-collection.

8
• Java, with the help of exception handling captures all types of serious errors and
eliminates any risk of crashing the system.
Secure
• Java provides a “firewall” between a networked application and your computer.
• When a Java Compatible Web browser is used, downloading can be done safely
without fear of viral infection or malicious intent.
• Java achieves this protection by confining a Java program to the java execution
environment and not allowing it to access other parts of the computer.
Architecture Neutral
• Java language and Java Virtual Machine helped in achieving the goal of “write once; run
anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.
Portable
• Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
• It helps in generating Portable executable code.
High Performance
• Java performance is high because of the use of bytecode.
• The bytecode was used, so that it was easily translated into native machine code.
Multithreaded
• Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.
• Java run-time system comes with tools that support multiprocess synchronization
used to construct smoothly interactive systems.
Dynamic
• Java is capable of linking in new class libraries, methods, and objects.
• It can also link native methods (the functions written in other languages such as C and
C++).

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Object

9
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type
of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
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 the parent class. Moreover, you can add new methods and fields in your current class
also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
The 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. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

10
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
• Single Inheritance
• Multilevel Inheritance
• Hierarchical. Inheritance
• Multiple Inheritance
• Hybrid Inheritance

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
Or
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.

11
Multilevel Inheritance
As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
Or
In Hierarchical Inheritance, one class is inherited by many sub classes.

12
Hierarchical Inheritance
As per above example, Class B, C, and D inherit the same class A.

File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

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 the same method and you call it from child class object, there will be
ambiguity to call the 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.
Or
In Multiple Inheritance, one class extending more than one class. Java does not support
multiple inheritance.

13
Multiple Inheritance
As per above diagram, Class C extends Class A and Class B both.

• 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?
• }
• }

Output

Compile Time Error

Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance.

14
Hybrid Inheritance
As per above example, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Note: Java doesn't support hybrid/Multiple inheritence

Method Overloading in Java


If a class has multiple methods having same name but different in 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 behavior 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
Note:In java, Method Overloading is not possible by changing the return type of the method
only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.

15
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9

Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum()
method should be called?

16
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler
time error if you declare the same method having same parameters.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, 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 are known as encapsulation.
For example, a 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.
Java Data Types
As explained in the previous chapter, a variable in Java must be a specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Data types are divided into two groups:
• Primitive data types - includes byte, short, int, long, float, double, boolean and char
• Non-primitive data types - such as String, Arrays and Classes (you will learn more
about these in a later chapter)
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional
methods.
There are eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15

17
decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values

Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on
the numeric value.
Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for
whole numbers) and double (for floating point numbers). However, we will describe them
all as you continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead
of int or other integer types to save memory when you are certain that the value will be
within -128 and 127:
Example
byte myNum = 100;
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
short myNum = 5000;
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general,
and in our tutorial, the int data type is the preferred data type when we create variables
with a numeric value.
Example
int myNum = 100000;
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example
long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
You should use a floating point type whenever you need a number with a decimal, such as
9.99 or 3.14515.

18
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "f":
Example
float myNum = 5.75f;
System.out.println(myNum);
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that
you should end the value with a "d":
Example
double myNum = 19.99d;
System.out.println(myNum);
Use float or double?
The precision of a floating point value indicates how many digits the value can have after
the decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of
10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);

Booleans
A boolean data type is declared with the boolean keyword and can only take the
values true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Boolean values are mostly used for conditional testing, which you will learn more about in
a later chapter.

Characters
The char data type is used to store a single character. The character must be surrounded
by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);
Alternatively, you can use ASCII values to display certain characters:
Example
char a = 65, b = 66, c = 67;

19
System.out.println(a);
System.out.println(b);
System.out.println(c);
Tip: A list of all ASCII values can be found in our ASCII Table Reference.

Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
The String type is so much used and integrated in Java, that some call it "the
special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The
String object has methods that is used to perform certain operations on strings. Don't
worry if you don't understand the term "object" just yet. We will learn more about
strings and objects in a later chapter.

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with
an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types
have all the same size.
Variables in java
There are different types of variables in Java. They are as follows:
1. Instance Variables (Non-Static Fields)
Objects store their individual states in “non-static fields”, that is, fields declared without
the static keyword.
Non-static fields are also known as instance variables because their values are unique to
each instance of a class. For example, the currentSpeed of one bicycle is independent from
the currentSpeed of another.
2. Class Variables (Static Fields)
A class variable is any field declared with the static modifier; this tells the compiler that
there is exactly one copy of this variable in existence, regardless of how many times the
class has been instantiated. A field defining the number of gears for a particular kind of
bicycle could be marked as static since, conceptually, the same number of gears will apply
to all instances. The code static int numGears = 6; would create such a static field.

20
3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;). There is no special
keyword designating a variable as local; that determination comes entirely from the
location in which the variable is declared—between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are declared;
they are not accessible from the rest of the class.
4. Parameters
They are the variables that are passed to the methods of a class.
Variable Declaration
Identifiers are the names of variables. They must be composed of only letters, numbers, the
underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only
begin with a letter, the underscore, or the dollar sign. A variable cannot begin with a
number. All variable names are case sensitive.
Syntax for variable declaration
datatype1 variable1, datatype2 variable2, … datatypen variablen;
For example:
int a, char ch;
Initialisation
Variables can be assigned values in the following way: Variablename = value;
For example;
ch='a';
a=0;
Arrays
Arrays: An array represents a group of elements of same data type.
Arrays are generally categorized into two types.
• Single Dimensional arrays (or 1 Dimensional arrays or 1D) ·
• Multi-Dimensional arrays (or 2 Dimensional arrays or 2D, 3 Dimensional arrays or
3D, …)
Single Dimensional Arrays: A one dimensional array or single dimensional array
represents a row or a column of elements. For example, the marks obtained by a student in
5 different subjects can be represented by a 1D array.
· We can declare a one dimensional array and directly store elements at the time of its
declaration, as:
int marks[] = {15, 20, 25, 30, 50};
· We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as:
int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as: int marks [] = new int [5];
The following program, Printarr, creates an array of integers, puts some values in it, and
prints each value to standard output.

class Printarr {
public static void main(String[] args) {
// declares an array of integers

21
int[ ] A;

// allocates memory for 5 integers


A = new int[5];

// initialize elements
A[0] = 15;//first element

A[1] = 20;//second element

A[2] = 25;//third element

A[3] = 30;//fourth element

A[4] = 50;//fifth element

System.out.println("Element at index 0: "


+ A[0]);
System.out.println("Element at index 1: "
+ A[1]);
System.out.println("Element at index 2: "
+ A[2]);
System.out.println("Element at index 3: "
+ A[3]);
System.out.println("Element at index 4: "
+ A[4]);
}
}
The output from this program is:
Element at index 0: 15
Element at index 1: 20
Element at index 2: 25
Element at index 3: 30
Element at index 4: 50

Multi-Dimensional Arrays (2D, 3D … arrays):


Multi dimensional arrays represent 2D, 3D … arrays. A two dimensional array is a
combination of two or more (1D) one dimensional arrays. A three dimensional array is a
combination of two or more (2D) two dimensional arrays.
Two Dimensional Arrays (2d array): A two dimensional array represents several rows and
columns of data. To represent a two dimensional array, we should use two pairs of square
braces [ ] [ ] after the array name. For example, the marks obtained by a group of students
in five different subjects can be represented by a 2D array.
We can declare a two dimensional array and directly store elements at the time of its
declaration, as: int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80,
69} };

22
We can create a two dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int marks[ ] [ ]; //declare marks
array marks = new int[3][5]; //allot memory for storing 15 elements.
These two statements also can be written as:
int marks [ ][ ] = new int[3][5];

Program 2: Write a program to take a 2D array and display its elements in the form
of a matrix. //Displaying a 2D array as a matrix

class Matrix
{
public static void main(String args[])
{ //take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} }; // display the array elements
for (int i = 0 ; i < 2 ; i++)
{
System.out.println ("");
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}}}
Output:
123
456

Operators in java
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example above,
it can also be used to add together a variable and a value, or a variable and another
variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Java divides the operators into the following groups:


• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

23
• Unary Operator
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example


+ Addition Adds together two values x+y
Subtracts one value from
- Subtraction another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value from another x/y
% Modulus Returns the division remainder x%y
Increases the value of a variable
++ Increment by 1 ++x
Decreases the value of a
-- Decrement variable by 1 --x

Java Arithmetic Operators


Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2
0
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a a
variable called x:
Example
int x = 10;
A list of all assignment operators:
Operator Example Same As

24
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x = x / 3
%= x %= 3x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Example program

class OperatorExample{

public static void main(String args[]){

int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)

System.out.println(a);
System.out.println(b);
}}
Output:
14
16

Java Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x<y
>= Less than or
equal to x <= y
Java Logical Operators
Logical operators are used to determine the logic between variables or values:
Operator Name Description Example
&& Logical Returns true if both statements x < 5 && x < 10
and are true
|| Logical or Returns true if one of the x < 5 || x < 4

25
statements is true
! Logical Reverse the result, returns false if !(x < 5 && x < 10)
not the result is true

Bitwise operators in Java


Bitwise operators are used to perform manipulation of individual bits of a number. They
can be used with any of the integral types (char, short, int, etc). They are used when
performing update and query operations of Binary indexed tree.
1.Bitwise OR (|) –
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e, if
either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2.Bitwise AND (&) –
This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of input values,
i.e, if both bits are 1, it gives 1, else it gives 0.
For example,

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

Bitwise XOR (^) –


This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e,
if corresponding bits are different, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
26
________
0010 = 2 (In decimal)

Bitwise Complement (~) –


This operator is unary operator, denoted by ‘~’. It returns the one’s compliment
representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1,
and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)

Bitwise Compliment Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -
6.

// Java program to illustrate


// bitwise operators
public class operators {
public static void main(String[] args)
{
//Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise and
// ~0101=1010
// will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a);

27
// can also be combined with
// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5

Java expressions
Expressions are constructed from operands and operators. The operators of an
expression indicate which operations to apply to the operands. The order of evaluation of
operators in an expression is determined by the precedence and associativity of the
operators.
An operator is a special symbol which indicates a certain process is carried out. Operators
in programming languages are taken from mathematics. Programmers work with data. The
operators are used to process data. An operand is one of the inputs (arguments) of an
operator.

Control Statements in Java

A control statement works as a determiner for deciding the next task of the other
statements whether to execute or not. An ‘If’ statement decides whether to execute a
statement or which statement has to execute first between the two. In Java, the control
statements are divided into three categories which are selection statements, iteration
statements, and jump statements. A program can execute from top to bottom but if we use
a control statement. We can set order for executing a program based on values and logic
• Decision Making in Java
• Simple if Statement
• if…else Statement
• Nested if statement
• if...else if…else statement
• Switch statement
• While
• Do…while
• For
• For-Each Loop
1. Branching Statements in Java
• Break
28
• Continue
• Return
Decision Making in Java
Decision making statements are statements which decides what to execute and when. They
are similar to decision making in real time. Control flow statements control the flow of a
program’s execution. Here flow of execution will be based on state of a program. We have 4
decision making statements available in Java.
Simple if Statement
Simple if statement is the basic of decision-making statements in Java. It decides if certain
amount of code should be executed based on the condition.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false
Example:
class ifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Output:
After if statement
if…else Statement
In if…else statement, if condition is true then statements in if block will be executed but if it
comes out as false then else block will be executed.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Example:
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("x is greater than 10");
else
System.out.println("x is less than 10");
System.out.println("After if else statement");

29
}
}
Output:
x is less than 10
After if else statement
Nested if statement
Nested if statement is if inside an if block. It is same as normal if…else statement but they
are written inside another if…else statement.
Syntax:
if (condition1) {
Statemen 1; //executed when condition1 is true
if (condition2) {
Statement 2; //executed when condition2 is true
}
else {
Statement 3; //executed when condition2 is false
}
}
Example:
class nestedifTest
{
public static void main(String args[])
{
int x = 25;

if (x > 10)
{
if (x%2==0)
System.out.println("x is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else
{
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
}
}
Output:
i is greater than 10 and odd number
After nested if statement
if...else if…else statement
if…else if statements will be used when we need to compare the value with more than 2
conditions. They are executed from top to bottom approach. As soon as the code finds the

30
matching condition, that block will be executed. But if no condition is matching then the
last else statement will be executed.
Syntax:
if (condition2) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
<span style="white-space:pre"> </span>Statement 2; // if condition2 becomes true then
this will be executed
}
.
.
else {
Statement 3; //executed when no matching condition found
}
Example:
class ifelseifTest
{
public static void main(String args[])
{
int x = 2;

if (x > 10)
{
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else
{
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
Output:
i is less than 10
After if else if ladder statement
Switch statement
Java switch statement compares the value and executes one of the case blocks based on the
condition. It is same as if…else if ladder. Below are some points to consider while working
with switch statements:
• case value must be of the same type as expression used in switch statement
• case value must be a constant or literal. It doesn’t allow variables

31
• case values should be unique. If it is duplicate, then program will give compile time
error
Let us understand it through one example.
class switchDemo{
public static void main(String args[]){
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}
Looping Statements in Java
Looping statements are the statements which executes a block of code repeatedly until
some condition meet to the criteria. Loops can be considered as repeating if statements.
There are 3 types of loops available in Java.
While
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true
then executes the body of loop. This is repeated until the condition becomes false.
Condition in while loop must be given as a Boolean expression. If int or string is used
instead, compile will give the error.
Syntax:
while (condition)
{
statement1;
}
Example:
class whileLoopTest
{
public static void main(String args[])

32
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Output:
1
3
5
7
9
Do…while
Do…while works same as while loop. It has only one difference that in do…while, condition
is checked after the execution of the loop body. That is why this loop is considered as exit
control loop. In do…while loop, body of loop will be executed at least once before checking
the condition
Syntax:
do{
statement1;
}while(condition);
Example: here
class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;

do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}
Output:
10
For
It is the most common and widely used loop in Java. It is the easiest way to construct a loop
structure in code as initialization of a variable, a condition and increment/decrement are
declared only in a single line of code. It is easy to debug structure in Java.
Syntax:
for (initialization; condition; increment/decrement)

33
{
statement;
}
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
1
2
3
4
5
For-Each Loop
For-Each loop is used to traverse through elements in an array. It is easier to use because
we don’t have to increment the value. It returns the elements from the array or collection
one by one.
Example:
class foreachDemo{
public static void main(String args[]){
int a[] = {10,15,20,25,30};
for (int i : a) {
System.out.println(i);
}
}
Output:
10
15
20
25
30

Branching Statements in Java


Branching statements jump from one statement to another and transfer the execution flow.
There are 3 branching statements in Java.
Break
Break statement is used to terminate the execution and bypass the remaining code in loop.
It is mostly used in loop to stop the execution and comes out of loop. When there are nested
loops then break will terminate the innermost loop.
Example:
class breakTest

34
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}
Output:
0
1
2
3
4
After loop
Continue
Continue statement works same as break but the difference is it only comes out of loop for
that iteration and continue to execute the code for next iterations. So it only bypasses the
current iteration.
Example:
class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
// only even numbers will be printed
System.out.print(j + " ");
}
}
}
Output:
02468
Return
Return statement is used to transfer the control back to calling method. Compiler will
always bypass any sentences after return statement. So, it must be at the end of any
method. They can also return a value to the calling method.
Example: Here method getwebURL() returns the current URL to the caller method.

35
public String getwebURL()
{
String vURL= null;
try {
vURL= driver.getCurrentUrl();
}
catch(Exception e) {
System.out.println("Exception occured while getting the current url :
"+e.getStackTrace());
}
return vURL;
}
Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
MyClass.java

Create a class named "MyClass" with a variable x:

public class MyClass {

int x = 5;

Create an Object

In Java, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name, and use
the keyword new:

36
Example

Create an object called "myObj" and print the value of x:

public class MyClass {

int x = 5;

public static void main(String[] args) {

MyClass myObj = new MyClass();

System.out.println(myObj.x);

Out put:5
Java Class Methods

You learned from the Java Methods chapter that methods are declared within a class, and
that they are used to perform certain actions:

Example

Create a method named myMethod() in MyClass:

public class MyClass {

static void myMethod() {

System.out.println("Hello World!");

myMethod() prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;

Example

Inside main, call myMethod():

public class MyClass {

37
static void myMethod() {

System.out.println("Hello World!");

public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

String Length

A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with
the length() method:

Example
MyClass.java

public class MyClass {


public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}

Result:
The length of the txt string is: 26

String upper and lower


MyClass.java

38
public class MyClass {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}

Result:
HELLO WORLD
hello world

String Concatenation

The + operator can be used between strings to combine them. This is


called concatenation:

Example
MyClass.java

public class MyClass {


public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}

Result:
John Doe

note that we have added an empty text (" ") to create a space between firstName and
lastName on print.

You can also use the concat() method to concatenate two strings:

Example
MyClass.java

public class MyClass {


public static void main(String[] args) {

39
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
}
}

Result:
John Doe

Java Inheritance
Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:

• subclass (child) - the class that inherits from another class


• superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

Example
Car.java

class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang";
public static void main(String[] args) {
Car myFastCar = new Car();
myFastCar.honk();
System.out.println(myFastCar.brand + " " + myFastCar.modelName);
}
}

40
Result:
Tuut, tuut!
Ford Mustang

Access Modifiers in Java

As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor , variable , method or data member. There are four types of access modifiers
available in java:
• Default – No keyword required
• Private
• Protected
• Public

• Default: When no access modifier is specified for a class , method or data member –
It is said to be having the default access modifier by default.

• The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
In this example, we will create two packages and the classes in the packages will be
having the default access modifiers and we will try to access a class from one package
from a class of second package.

//Java program to illustrate default modifier
package p1;

//Class Geeks is having Default access modifier


class Geek
{
void display()
{
System.out.println("Hello World!");
}
}

//Java program to illustrate error while


//using class from different package with
//default modifier
package p2;
import p1.*;

41
//This class is having default access modifier
class GeekNew
{
public static void main(String args[])
{
//accessing class Geek from package p1
Geeks obj = new Geek();

obj.display();
}
}
Output:
Compile time error
• Private: The private access modifier is specified using the keyword private.
• The methods or data members declared as private are accessible only within
the class in which they are declared.
• Any other class of same package will not be able to access these members.
• Top level Classes or interface can not be declared as private because
• private means “only visible within the enclosing class”.
• protected means “only visible within the enclosing class and any
subclasses”
Hence these modifiers in terms of application to classes, they apply only to
nested classes and not on top level classes
In this example, we will create two classes A and B within same package p1. We will
declare a method in class A as private and try to access this method from class B and
see
//Java program to illustrate error while
//using class from different package with
//private modifier
package p1;

class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}

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

42
{
A obj = new A();
//trying to access private method of another class
obj.display();
}
}
Output:
error: display() has private access in A
obj.display();

• protected: The protected access modifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible within
same package or sub classes in different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public,
to access it in p2. The method display in class A is protected and class B is inherited
from class A and this protected method is then accessed by creating an object of class
B.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate
//protected modifier
package p1;

//Class A
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate
//protected modifier
package p2;

43
import p1.*; //importing all classes in package p1

//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

}
Output:
GeeksforGeeks

• public: The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods or data members which are declared as public are accessible
from every where in the program. There is no restriction on the scope of a
public data members.

//Java program to illustrate


//public modifier
package p1;
public class A
{
public void display()
{
System.out.println("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B
{
public static void main(String args[])
{
A obj = new A;
obj.display();
}
}
Output:

44
GeeksforGeeks

Constructors in Java

Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of Object
creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say
length, breadth, and height). But when it comes to creating its object(i.e Box will now exist
in computer’s memory), then can a box be there with no value defined for its dimensions.
The answer is no.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default constructor).
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be
default constructor) is invoked to assign initial values to the data members of the same
class.
A constructor is invoked at the time of object or instance creation. For Example:
class Geek
{
.......

// A Constructor
new Geek() {}

.......
}

// We can create an object of the above class


// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
Rules for writing Constructor:
• Constructor(s) of a class must has same name as the class name in which it resides.
• A constructor in Java can not be abstract, final, static and Synchronized.

45
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.

Types of constructor
There are two type of constructor in Java:
• No-argument constructor: A constructor that has no parameter is known as default
constructor. If we don’t define a constructor in a class, then compiler creates default
constructor(with no arguments) for the class. And if we write a constructor with
arguments or no-arguments then the compiler does not create a default constructor.
Default constructor provides the default values to the object like 0, null, etc.
depending on the type.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;

class Geek
{
int num;
String name;

// this would be invoked while an object


// of that class is created.
Geek()
{
System.out.println("Constructor called");
}
}

class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();

// Default constructor provides the default


// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}

46
Output :
Constructor called
null
0
• Parameterized Constructor: A constructor that has parameters is known as
parameterized constructor. If we want to initialize fields of the class with your own
values, then use a parameterized constructor.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;

class Geek
{
// data members of the class.
String name;
int id;

// constructor would initialize data members


// with the values of passed arguments while
// object of that class created.
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}

class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name +
" and GeekId :" + geek1.id);
}
}
Output:

47
GeekName :adam and GeekId :1
Does constructor return any value?
There are no “return value” statements in constructor, but constructor returns current
class instance. We can write ‘return’ inside a constructor.

Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of the
parameters and order of the parameters.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;

class Geek
{
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one " +
"argument - String : " + name);
}

// constructor with two arguments


Geek(String name, int age)
{

System.out.println("Constructor with two arguments : " +


" String and Integer : " + name + " "+ age);

// Constructor with one argument but with different


// type than previous..
Geek(long id)
{
System.out.println("Constructor with one argument : " +
"Long : " + id);
}

48
}

class GFG
{
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
Geek geek2 = new Geek("Shikhar");

// Invoke the constructor with two arguments


Geek geek3 = new Geek("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
Geek geek4 = new Geek(325614567);
}
}
Output:
Constructor with one argument - String : Shikhar
Constructor with two arguments - String and Integer : Dharmesh 26
Constructor with one argument - Long : 325614567

Creating a Multilevel Inheritance Hierarchy in Java


Inheritance involves an object acquiring the properties and behaviour of another object. So
basically, using inheritance can extend the functionality of the class by creating a new class
that builds on the previous class by inheriting it.
Multilevel inheritance is when a class inherits a class which inherits another class. An
example of this is class C inherits class B and class B in turn inherits class A.
A program that demonstrates a multilevel inheritance hierarchy in Java is given as follows:
Example
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {

49
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
Output
This is class A
This is class B
This is class C

Java Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):

MyMainClass.java

class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

50
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

class MyMainClass {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

Result:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Java Pylymorphism
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.

Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded
with the respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.

51
Example

import java.util.Arrays;

public class AdHocPolymorphismExample {

void sorting(int[] list) {


Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names) {
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
}

public static void main(String[] args) {

AdHocPolymorphismExample obj = new AdHocPolymorphismExample();


int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array

String[] names = {"rama", "raja", "shyam", "seeta"};


obj.sorting(names); // Calling with String array
}
}

When we run this code, it produce the following output.

52
Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.
Example
class ParentClass{

int num = 10;

void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


obj.showData();

obj = new ChildClass();


obj.showData();

}
}

53
When we run this code, it produce the following output.

Method Overriding in Java


• Understanding the problem without method overriding
• Can we override the static method
• Method overloading vs. method overriding
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 a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an 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.

54
• //Java Program to demonstrate why we need method overriding
• //Here, we are calling the method of parent class with child
• //class object.
• //Creating a parent class
• class Vehicle{
• void run(){System.out.println("Vehicle is running");}
• }
• //Creating a child class
• class Bike extends Vehicle{
• public static void main(String args[]){
• //creating an instance of child class
• Bike obj = new Bike();
• //calling the method with child class instance
• 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 are
the same, and there is IS-A relationship between the classes, so there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:

55
Bike is running safely

A real example of Java Method Overriding


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

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
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());

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

forms of inheritance-
The inheritance concept used for the number of purposes in the java programming
language. One of the main purposes is substitutability. The substitutability means that
when a child class acquires properties from its parent class, the object of the parent class
may be substituted with the child class object. For example, if B is a child class of A,
anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.
• Specialization
• Specification
• Construction
• Eextension
• Limitation
• Combination

Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.

Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't
implement them. The java provides concepts like abstract and interfaces to support this
form of inheritance. It holds the principle of substitutability.

Construction
This is another form of inheritance where the child class may change the behavior defined
by the parent class (overriding). It does not hold the principle of substitutability.

Eextension
This is another form of inheritance where the child class may add its new properties. It
holds the principle of substitutability.

57
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does not hold the principle of substitutability.

Combination
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.

benefits of inheritance
• Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
• Inheritance can save time and effort as the main code need not be written again.
• Inheritance provides a clear model structure which is easy to understand.
• An inheritance leads to less development and maintenance costs.
• With inheritance, we will be able to override the methods of the base class so that
the meaningful implementation of the base class method can be designed in the
derived class. An inheritance leads to less development and maintenance costs.
• In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.

Costs of Inheritance
• Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
• Inheritance makes the two classes (base and inherited class) get tightly coupled.
This means one cannot be used independently of each other.
• The changes made in the parent class will affect the behavior of child class too.
• The overuse of inheritance makes the program more complex.

UNIT – 2
Packages
Defining a Package
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −

58
• java.lang − bundles the fundamental classes
• java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It
is a good practice to group related classes implemented by you so that a programmer can
easily determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier
to locate the related classes.

Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as
shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.

Example
Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes
and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */

59
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and
these class files will be placed in it as shown below.

You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels

The import Keyword


If a class wants to use another class in the same package, the package name need not be
used. Classes in the same package find each other without any special syntax.

Example
Here, a class named Boss is added to the payroll package that already contains Employee.
The Boss can then refer to the Employee class without using the payroll prefix, as
demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee(Employee e) {

60
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must
then use one of the following techniques for referring to a class in a different package.
• The fully qualified name of the class can be used. For example −
payroll.Employee
• The package can be imported using the import keyword and the wild card (*). For
example −
import payroll.*;
• The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Note − A class file can contain any number of import statements. The import statements
must appear after the package statement and before the class declaration.

The Directory Structure of Packages


Two major results occur when a class is placed in a package −
• The name of the package becomes a part of the name of the class, as we just
discussed in the previous section.
• The name of the package must match the directory structure where the
corresponding bytecode resides.
Here is simple way of managing your files in Java −
Put the source code for a class, interface, enumeration, or annotation type in a text file
whose name is the simple name of the type and whose extension is .java.
For example −
// File Name : Car.java
package vehicle;

public class Car {


// Class implementation.
}
Now, put the source file in a directory whose name reflects the name of the package to
which the class belongs −
....\vehicle\Car.java
Now, the qualified class name and pathname would be as follows −
• Class name → vehicle.Car
• Path name → vehicle\Car.java (in windows)

61
In general, a company uses its reversed Internet domain name for its package names.
Example − A company's Internet domain name is apple.com, then all its package names
would start with com.apple. Each component of the package name corresponds to a
subdirectory.
Example − The company had a com.apple.computers package that contained a Dell.java
source file, it would be contained in a series of subdirectories like this −
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class,
interface and enumeration defined in it. The base name of the output file is the name of the
type, and its extension is .class.
For example −
// File Name: Dell.java
package com.apple.computers;

public class Dell {


}

class Ups {
}
Now, compile this file as follows using -d option −
$javac -d . Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that
reflect the package name. However, the path to the .class files does not have to be the same
as the path to the .java source files. You can arrange your source and class directories
separately, as −
<path-one>\sources\com\apple\computers\Dell.java

<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give access to the classes directory to other programmers
without revealing your sources. You also need to manage source and class files in this
manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your
program uses.

62
The full path to the classes directory, <path-two>\classes, is called the class path, and is
set with the CLASSPATH system variable. Both the compiler and the JVM construct the
path to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers,
then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\
computers.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current
directory and the JAR file containing the Java platform classes so that these directories are
automatically in the class path.

Set CLASSPATH System Variable


To display the current CLASSPATH variable, use the following commands in Windows and
UNIX (Bourne shell) −
• In Windows → C:\> set CLASSPATH
• In UNIX → % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use −
• In Windows → C:\> set CLASSPATH =
• In UNIX → % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable −
• In Windows → set CLASSPATH = C:\users\jack\java\classes
• In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH

Access protection in java packages


In java, the access modifiers define the accessibility of the class and its members. For
example, private members are accessible within the same class members only. Java has
four access modifiers, and they are default, private, protected, and public.

In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the
accessibility of class members across the different packages.

In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.

• The public members can be accessed everywhere.


• The private members can be accessed only inside the same class.

63
• The protected members are accessible to every child class (same package or other
packages).
• The default members are accessible within the same package but not outside the
package.

Let's look at the following example java code.

Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

class ChildClass extends ParentClass{

void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

64
When we run this code, it produce the following output.
Inside ParentClass
a = 10
b = 20
c = 30
d=40
Inside ChildClass
a=10
b=20
c=30

Import Package
Package is a collection of related classes. Java uses package to group related classes,
interfaces and sub-packages in any Java project.

We can assume package as a folder or a directory that is used to store similar files.

In Java, packages are used to avoid name conflicts and to control access of class, interface
and enumeration etc. Using package it becomes easier to locate the related classes and it
also provides a good structure for projects with hundreds of classes and other files.

Lets understand it by a simple example, Suppose, we have some math related classes and
interfaces then to collect them into a simple place, we have to create a package.

Types Of Java Package


Package can be built-in and user-defined, Java provides rich set of built-in packages in form
of API that stores related classes and sub-packages.

Built-in Package: math, util, lang, i/o etc are the example of built-in packages.
User-defined-package: Java package created by user to categorize their project's classes
and interface are known as user-defined packages.
Packages in java

How to Create a Package


Creating a package in java is quite easy, simply include a package command followed by
name of the package as the first statement in java source file.

package mypack;
public class employee
{
String empId;
String name;
}
The above statement will create a package woth name mypack in the project directory.

65
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.

Additional points about package:


Package statement must be first statement in the program even before the import
statement.
A package is always defined as a separate folder having the same name as the package
name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package must be declared
public.
All classes within the package must have the package statement as its first line.
All classes of the package must be compiled before use.
Example of Java packages
Now lets understand package creation by an example, here we created a leanjava package
that stores the FirstProgram class file.

//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package example");
}
}
How to compile Java programs inside packages?
This is just like compiling a normal java program. If you are not using any IDE, you need to
follow the steps given below to successfully compile your packages:

javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like 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?


To run the compiled class that we compiled using above command, we need to specify
package name too. Use the below command to run the class file.

java learnjava.FirstProgram

Welcome to package example

After running the program, we will get “Welcome to package example” message to the
console. You can tally that with print statement used in the program.

66
How to import Java Package
To import java package into a class, we need to use java import keyword which is used to
access package and its classes into the java program.

Use import to access built-in and user-defined packages into your java source file so that
your class can refer to a class that is in another package by directly using its name.

There are 3 different ways to refer to any class that is present in a different package:

without import the package


import package with specified class
import package with all classes
Lets understand each one with the help of example.

Accessing package without import keyword


If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the same
package will not be accessible. For this approach, there is no need to use the import
statement. But you will have to use the fully qualified name every time you are accessing
the class or the interface. This is generally used when two packages have classes with same
names. For example: java.util and java.sql packages contain Date class.

Example
In this example, we are creating a class A in package pack and in another class B, we are
accessing it while creating object of class A.

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

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

Hello

67
Import the Specific Class
Package can have many classes but sometimes we want to access only specific class in our
program in that case, Java allows us to specify class name along with package name. If we
use import packagename.classname statement then only the class with name classname in
the package will be available for use.

Example:
In this example, we created a class Demo stored into pack package and in another class
Test, we are accessing Demo class by importing package name with class name.

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

//save by Test.java
package mypack;
import pack.Demo;
class Test {
public static void main(String args[]) {
Demo obj = new Demo();
obj.msg();
}
}

Hello

Import all classes of the package


If we use packagename.* statement, then all the classes and interfaces of this package will
be accessible but the classes and interface inside the sub-packages will not be available for
use.

The import keyword is used to make the classes of another package accessible to the
current package.

Example :
In this example, we created a class First in learnjava package that access it in another class
Second by using import keyword.

//save by First.java
package learnjava;
public class First{
public void msg() {

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

//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}

Hello

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare
an interface −

Example
Following is an example of an interface −

/* File name : NameOfInterface.java */


import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
Interfaces have the following properties −

An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.

69
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.

Methods in an interface are implicitly public.

Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}

Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.

Example 1: Java Interface


interface Polygon {
void getArea(int length, int breadth);
}

// implement the Polygon interface


class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output

The area of the rectangle is 30


In the above example, we have created an interface named Polygon. The interface contains
an abstract method getArea().

70
Here, the Rectangle class implements Polygon. And, provides the implementation of the
getArea() method.

Example 2: Java Interface


// create an interface
interface Language {
void getName(String name);
}

// class implements interface


class ProgrammingLanguage implements Language {

// implementation of abstract method


public void getName(String name) {
System.out.println("Programming Language: " + name);
}
}

class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");
}
}
Output

Programming Language: Java


In the above example, we have created an interface named Language. The interface
includes an abstract method getName().

Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.

Implementing Multiple Interfaces


In Java, a class can also implement multiple interfaces. For example,

interface A {
// members of A
}

interface B {
// members of B
}

class C implements A, B {
// abstract members of A

71
// abstract members of B
}
Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is used for
extending interfaces. For example,

interface Line {
// members of Line interface
}

// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class implements
Polygon, it should provide implementations for all the abstract methods of both Line and
Polygon.

Extending Multiple Interfaces


An interface can extend multiple interfaces. For example,

interface A {
...
}
interface B {
...
}

interface C extends A, B {
...
}

Nested or Inner interfaces in Java

An interface which is declared inside another interface or class is called nested interface.
They are also known as inner interface. Since nested interface cannot be accessed directly,
the main purpose of using them is to resolve the namespace by grouping related interfaces
(or related interface and class) together. This way, we can only call the nested interface by
using outer class or outer interface name followed by dot( . ), followed by the interface
name.

Example: Entry interface inside Map interface is nested. Thus we access it by calling
Map.Entry.

Note:

72
Nested interfaces are static by default. You don’t have to mark them static explicitly as it
would be redundant.
Nested interfaces declared inside class can take any access modifier, however nested
interface declared inside interface is public implicitly.
Example 1: Nested interface declared inside another interface
interface MyInterfaceA{
void display();
interface MyInterfaceB{
void myMethod();
}
}

class NestedInterfaceDemo1
implements MyInterfaceA.MyInterfaceB{
public void myMethod(){
System.out.println("Nested interface method");
}

public static void main(String args[]){


MyInterfaceA.MyInterfaceB obj=
new NestedInterfaceDemo1();
obj.myMethod();
}
}
Output:
Nested interface method
Example 2: Nested interface declared inside a class
class MyClass{
interface MyInterfaceB{
void myMethod();
}
}

class NestedInterfaceDemo2 implements MyClass.MyInterfaceB{


public void myMethod(){
System.out.println("Nested interface method");
}

public static void main(String args[]){


MyClass.MyInterfaceB obj=
new NestedInterfaceDemo2();
obj.myMethod();
}
}
Output:

73
Nested interface method

Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous
flow of data. Streams are clean way to deal with input/output without having every part of
your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized

Java Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

74
BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Java Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.

75
These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

76
Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.

int read() throws IOException

Below is a simple example explaining character input.

class CharRead

public static void main( String args[])

BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));

char c = (char)br.read(); //Reading character

77
}

Reading Strings in Java


To read string we have to use readLine() function with BufferedReader class's object.

String readLine() throws IOException

Program to take String input from Keyboard in Java

import java.io.*;

class MyInput

public static void main(String[] args)

String text;

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

text = br.readLine(); //Reading String

System.out.println(text);

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;

78
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Java File Class

The File class is an abstract representation of file and directory pathname. A pathname can
be either absolute or relative.

The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.

79
Fields

Modifier Type Field Description

static String pathSeparator It is system-dependent path-separator


character, represented as a string for
convenience.

static char pathSeparatorChar It is system-dependent path-separator


character.

static String separator It is system-dependent default


name-separator character, represented
as a string for convenience.

static char separatorChar It is system-dependent default


name-separator character.

constructors

Constructor Description

File(File parent, String child) It creates a new File instance from a parent

abstract pathname and a child pathname string.

File(String pathname) It creates a new File instance by converting the

given pathname string into an abstract pathname.

File(String parent, String child) It creates a new File instance from a parent

pathname string and a child pathname string.

File(URI uri) It creates a new File instance by converting the

given file: URI into an abstract pathname.

80
Useful Methods
Modifier Method Description
and Type

static File createTempFile It creates an empty file in the default temporary-file directory, u
(String prefix, and suffix to generate its name.
String suffix)

boolean createNewFile( It atomically creates a new, empty file named by this


)
abstract pathname if and only if a file with this name

does not yet exist.

boolean canWrite() It tests whether the application can modify the file

denoted by this abstract pathname.String[]

boolean canExecute() It tests whether the application can execute the file

denoted by this abstract pathname.

boolean canRead() It tests whether the application can read the file denoted by

this abstract pathname.

boolean isAbsolute() It tests whether this abstract pathname is absolute.

boolean isDirectory() It tests whether the file denoted by this abstract pathname

is a directory.

boolean isFile() It tests whether the file denoted by this abstract pathname

is a normal file.

String getName() It returns the name of the file or directory denoted by this

abstract pathname.

String getParent() It returns the pathname string of this abstract pathname's

81
parent, or null if this pathname does not name a parent

directory.

Path toPath() It returns a java.nio.file.Path object constructed from the

this abstract path.

URI toURI() It constructs a file: URI that represents this abstract

pathname.

File[] listFiles() It returns an array of abstract pathnames denoting the files

in the directory denoted by this abstract pathname

long getFreeSpace() It returns the number of unallocated bytes in the partition

named by this abstract path name.

String[] list(FilenameFil It returns an array of strings naming the files and directories
ter filter)
in the directory denoted by this abstract pathname that

satisfy the specified filter.

boolean mkdir() It creates the directory named by this abstract pathname.

Java File Example 1


import java.io.*;
public class FileDemo {
public static void main(String[] args) {

try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}

82
} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:

New File is created!

Java File Example 2


import java.io.*;
public class FileDemo2 {
public static void main(String[] args) {

String path = "";


boolean bool = false;
try {
// createing new files
File file = new File("testFile1.txt");
file.createNewFile();
System.out.println(file);
// createing new canonical from file object
File file2 = file.getCanonicalFile();
// returns true if the file exists
System.out.println(file2);
bool = file2.exists();
// returns absolute pathname
path = file2.getAbsolutePath();
System.out.println(bool);
// if file exists
if (bool) {
// prints
System.out.print(path + " Exists? " + bool);
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}

Output:

83
testFile1.txt
/home/Work/Project/File/testFile1.txt
true
/home/Work/Project/File/testFile1.txt Exists? true

Java File Example 3


import java.io.*;
public class FileExample {
public static void main(String[] args) {
File f=new File("/Users/sonoojaiswal/Documents");
String filenames[]=f.list();
for(String filename:filenames){
System.out.println(filename);
}
}
}

Output:

"info.properties"
"info.properties".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
apache-tomcat-9.0.0.M19.tar
bestreturn_org.rtf
BIODATA.pages
BIODATA.pdf
BIODATA.png
struts2jars.zip
workspace

Java File Example 4


1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File dir=new File("/Users/sonoojaiswal/Documents");
5. File files[]=dir.listFiles();
6. for(File file:files){
7. System.out.println(file.getName()+" Can Write: "+file.canWrite()+"
8. Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");
9. }
10. }
11. }

84
Output:

"info.properties" Can Write: true Is Hidden: false Length: 15 bytes


"info.properties".rtf Can Write: true Is Hidden: false Length: 385 bytes
.DS_Store Can Write: true Is Hidden: true Length: 36868 bytes
.localized Can Write: true Is Hidden: true Length: 0 bytes
Alok news Can Write: true Is Hidden: false Length: 850 bytes
apache-tomcat-9.0.0.M19 Can Write: true Is Hidden: false Length: 476 bytes
apache-tomcat-9.0.0.M19.tar Can Write: true Is Hidden: false Length: 13711360 bytes
bestreturn_org.rtf Can Write: true Is Hidden: false Length: 389 bytes
BIODATA.pages Can Write: true Is Hidden: false Length: 707985 bytes
BIODATA.pdf Can Write: true Is Hidden: false Length: 69681 bytes
BIODATA.png Can Write: true Is Hidden: false Length: 282125 bytes
workspace Can Write: true Is Hidden: false Length: 1972 bytes

Reading and writing Files

FileWriter

FileWriter is useful to create a file writing characters into it.


 This class inherits from the OutputStream class.
 The constructors of this class assume that the default character encoding and the
default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
 FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
 FileWriter creates the output file , if it is not present already.
Constructors:
 FileWriter(File file) – Constructs a FileWriter object given a File object.
 FileWriter (File file, boolean append) – constructs a FileWriter object given a File
object.
 FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file
descriptor.
 FileWriter (String fileName) – constructs a FileWriter object given a file name.
 FileWriter (String fileName, Boolean append) – Constructs a FileWriter object
given a file name with a Boolean indicating whether or not to append the data written.
Methods:

 public void write (int c) throws IOException – Writes a single character.


 public void write (char [] stir) throws IOException – Writes an array of characters.
 public void write(String str)throws IOException – Writes a string.

85
 public void write(String str,int off,int len)throws IOException – Writes a portion
of a string. Here off is offset from which to start writing characters and len is number
of character to write.
 public void flush() throws IOException flushes the stream
 public void close() throws IOException flushes the stream first and then closes the
writer.
 Reading and writing take place character by character, which increases the
number of I/O operations and effects performance of the
system.BufferedWriter can be used along with FileWriter to improve speed of
execution.
 Following program depicts how to create a text file using FileWriter

// Creating a text File using FileWriter


import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";

// attach a file to FileWriter


FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Writing successful");
//close the file
fw.close();
}
}

FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
 This class inherit from the InputStreamReader Class.
 The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
 FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.

86
Constructors:
 FileReader(File file) – Creates a FileReader , given the File to read from
 FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter
to read from
 FileReader(String fileName) – Creates a new FileReader , given the name of the file
to read from
Methods:
 public int read () throws IOException – Reads a single character. This method will
block until a character is available, an I/O error occurs, or the end of the stream is
reached.
 public int read(char[] cbuff) throws IOException – Reads characters into an array.
This method will block until some input is available, an I/O error occurs, or the end of
the stream is reached.
 public abstract int read(char[] buff, int off, int len) throws IOException –Reads
characters into a portion of an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
 public void close() throws IOException closes the reader.
 public long skip(long n) throws IOException –Skips characters. This method will
block until some characters are available, an I/O error occurs, or the end of the stream
is reached.
Parameters:
n – The number of characters to skip
Following program depicts how to read from the ‘text’ file using FileReader

// Reading data from a file using FileReader


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;

// check if File exists or not


FileReader fr=null;
try
{
fr = new FileReader("text");
}

87
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}

// read from FileReader till the end of file


while ((ch=fr.read())!=-1)
System.out.print((char)ch);

// close the file


fr.close();
}
}

Java - RandomAccessFile

This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called file pointer,
by moving the cursor we do the read write operations. If end-of-file is reached before the
desired number of byte has been read than EOFException is thrown. It is a type of
IOException.

Constructor
Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and


file, String mode)
optionally to write to, the file specified by the File

argument.

RandomAccessFile(Strin Creates a random access file stream to read from, and


g name, String mode)
optionally to write to, a file with the specified name.

Method
Modifier and Method Method
Type

88
void close() It closes this random access file stream and releases

any system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated with

this file.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long It sets the file-pointer offset, measured from the beginning of this
pos)
file, at which the next read or write occurs.

void writeDouble It converts the double argument to a long using the


(double v)
doubleToLongBits method in class Double, and then writes that

long value to the file as an eight-byte quantity, high byte first.

void writeFloat(fl It converts the float argument to an int using the floatToIntBits
oat v)
method in class Float, and then writes that int value to the file as

a four-byte quantity, high byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long It sets the file-pointer offset, measured from the beginning of this
pos)
file, at which the next read or write occurs.

Example
1. import java.io.IOException;
89
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }

The myFile.TXT contains text "This class is used for reading and writing to random access
file."

after running the program it will contains

Next →← Prev
Java Console Class

The Java Console class is be used to get input from console. It provides methods to read
texts and passwords.

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.

90
Let's see a simple example to read text from console.

1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console class declaration

Let's see the declaration for Java.io.Console class:

1. public final class Console extends Object implements Flushable

Java Console class methods


Method Description

Reader reader() It is used to retrieve the reader object associated

with the console

String readLine() It is used to read a single line of text from the

console.

String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single

line of text from the console.

char[] readPassword() It is used to read password that is not being

displayed on the console.

char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the
args)
password that is not being displayed on the console.

Console format(String fmt, Object... args) It is used to write a formatted string to the console

output stream.

91
Console printf(String format, Object... It is used to write a string to the console output
args)
stream.

PrintWriter writer() It is used to retrieve the PrintWriter object

associated with the console.

void flush() It is used to flushes the console.

How to get the object of Console

System class provides a static method console() that returns the singleton 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.Console;
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: Nakul Jain


Welcome Nakul Jain

Java Console Example to read password


1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();

92
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: 123

Serialization in java
Java provides a mechanism, called object serialization where an object can be represented
as a sequence of bytes that includes the object's data as well as information about the
object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data
can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out −
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object −
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return
value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that
we discussed early on in the book. Suppose that we have the following Employee class,
which implements the Serializable interface −

Example
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;

93
public int number;

public void mailCheck() {


System.out.println("Mailing a check to " + name + " " + address);
}
}
Notice that for a class to be serialized successfully, two conditions must be met −
 The class must implement the java.io.Serializable interface.
 All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check the
documentation for the class. The test is simple: If the class implements java.io.Serializable,
then it is serializable; otherwise, it's not.

Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo
program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program
does not generate any output, but study the code and try to determine what the program
is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the
file a .ser extension.

Example
import java.io.*;
public class SerializeDemo {

public static void main(String [] args) {


Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;

try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();

94
}
}
}

Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output −

Example
import java.io.*;
public class DeserializeDemo {

public static void main(String [] args) {


Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}

System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
This will produce the following result −

Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

95
What is Enumeration in Java?
Enumeration is basically a list of named constant. In Java, it defines a class type. It can
have constructors, methods and instance variables. It is created using the enum keyword.
By default, each enumeration constant is public, static and final. Even though enumeration
defines a class type and has constructors, you do not need to instantiate
an enum using the new variable. Enumeration variables are used and declared in the same
way as that of a primitive variable.

Or

The Enum in Java is a data type which contains a 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),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we should
have all constants in capital letters. So, we have enum constants in capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available
since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known
as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.

Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.

Points to remember for Java Enum


o Enum improves type safety
o Enum can be easily used in switch
o Enum can be traversed
o Enum can have fields, constructors and methods
o Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class

Simple Example of Java Enum


1. class EnumExample1{

96
2. //defining the enum inside the class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //main method
5. public static void main(String[] args) {
6. //traversing the enum
7. for (Season s : Season.values())
8. System.out.println(s);
9. }}

Output:

WINTER
SPRING
SUMMER
FALL

Let us see another example of Java enum where we are using value(), valueOf(), and
ordinal() methods of Java enum.

1. class EnumExample1{
2. //defining enum within class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //creating the main method
5. public static void main(String[] args) {
6. //printing all enum
7. for (Season s : Season.values()){
8. System.out.println(s);
9. }
10. System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
11. System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
12. System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
13.
14. }}

Output:

WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2

Note: Java compiler internally adds values(), valueOf() and ordinal() methods within the
enum at compile time. It internally creates a static and final class for the enum.

97
What is the purpose of the values() method in the 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.

What is the purpose of the valueOf() method in the enum?

The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant enum.

What is the purpose of the ordinal() method in the enum?

The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.

Autoboxing: Automatic conversion of primitive types to the object of their corresponding


wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object


of a wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double etc.

Primitive type Wrapper class


boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
When does the autoboxing and unboxing happens in Java

Autoboxing

: Lets see few cases with examples, where autoboxing happens.


Case 1: When a method is expecting a wrapper class object but the value that is passed as
parameter is a primitive type. For example in the below code, the method myMethod() is
expecting an object of Integer wrapper class, however we passed a primitive int type. The
program ran fine as compiler does the autoboxing (conversion of int to Integer)

class AutoboxingExample1
{
public static void myMethod(Integer num){

98
System.out.println(num);
}
public static void main(String[] args) {
/* passed int (primitive type), it would be
* converted to Integer object at Runtime
*/
myMethod(2);
}
}
Output:

Java Generic

Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid
types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String arrays
and so on, to sort the array elements.
Generic Methods
You can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. Following are the rules to define
Generic Methods −
 All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next
example).
 Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that
specifies a generic type name.
 The type parameters can be used to declare the return type and act as placeholders
for the types of the arguments passed to the generic method, which are known as
actual type arguments.
 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double
and char).
Example
Following example illustrates how we can print an array of different type using a single
Generic method −
public class GenericMethodTest {
// generic method printArray

99
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {


// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}
This will produce the following result −
Output
Array integerArray contains:
12345

Array doubleArray contains:


1.1 2.2 3.3 4.4

Array characterArray contains:


HELLO

UNIT - III
EXCEPTION HANDLING

Exception Handling in Java

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

100
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur

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 exceptions, its type and the difference between
checked and unchecked exceptions.

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an 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


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

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

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.

Hierarchy of Java Exception classes

101
The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are
given below:

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, 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 which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

102
3) Error

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

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

The "try" keyword is used to specify a block where we should place exception
try code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.

The "catch" block is used to handle the exception. It must be preceded by try
catch block which means we can't use catch block alone. It can be followed by finally
block later.

The "finally" block is used to execute the important code of the program. It is
finally
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It doesn't throw an


throws exception. It specifies that there may occur an exception in the method. It is
always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

103
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch
block.

Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following −

Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every try
block should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.

Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This will produce the following result −

104
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following −

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches,
in which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.

Example
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}

Catching Multiple Type of Exceptions


Since Java 7, you can handle more than one exception using a single catch block, this
feature simplifies the code. Here is how you would do it −
catch (IOException|FileNotFoundException ex) {
logger.log(ex);

105
throw ex;

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException −

Example
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the
exceptions are declared in a list separated by commas. For example, the following method
declares that it throws a RemoteException and an InsufficientFundsException −

Example
import java.io.*;
public class className {

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −

106
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
This will produce the following result −

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

The try-with-resources

107
Generally, when we use any resources like streams, connections, etc. we have to close
them explicitly using finally block. In the following program, we are reading data from a
file using FileReader and we are closing it using finally block.

Example
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

public static void main(String args[]) {


FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
try-with-resources, also referred as automatic resource management, is a new
exception handling mechanism that was introduced in Java 7, which automatically closes
the resources used within the try catch block.
To use this statement, you simply need to declare the required resources within the
parenthesis, and the created resource will be closed automatically at the end of the block.
Following is the syntax of try-with-resources statement.

Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
Following is the program that reads the data in a file using try-with-resources statement.

108
Example
import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

public static void main(String args[]) {


try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}
}
}
Following points are to be kept in mind while working with try-with-resources statement.
 To use a class with try-with-resources statement it should
implement AutoCloseable interface and the close() method of it gets invoked
automatically at runtime.
 You can declare more than one class in try-with-resources statement.
 While you declare multiple classes in the try block of try-with-resources statement
these classes are closed in reverse order.
 Except the declaration of resources within the parenthesis everything is the same
as normal try/catch block of a try block.
 The resource declared in try gets instantiated just before the start of the try-block.
 The resource declared at the try block is implicitly declared as final.

User-defined Exceptions
You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes −
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException
class.
We can define our own Exception class as below −
class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception.
These are considered to be checked exceptions. The
following InsufficientFundsException class is a user-defined exception that extends the
109
Exception class, making it a checked exception. An exception class is like any other class,
containing useful fields and methods.

Example
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception {


private double amount;

public InsufficientFundsException(double amount) {


this.amount = amount;
}

public double getAmount() {


return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount {


private double balance;
private int number;

public CheckingAccount(int number) {


this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException {


if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

public double getBalance() {


return balance;

110
}

public int getNumber() {


return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo {

public static void main(String [] args) {


CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);

try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo. This will produce the following result

Output
Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Termination or resumptive models

111
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.

 Termination Model
 Resumptive Model

Let's look into details of each exception model.

Termination Model

In the termination model, when a method encounters an exception, further processing in


that method is terminated and control is transferred to the nearest catch block that can
handle the type of exception encountered.

In other words we can say that in termination model the error is so critical there is no way
to get back to where the exception occurred.

Resumptive Model

The alternative of termination model is resumptive model. In resumptive model, the


exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the
exception is handled.

In resumptive model we may use a method call that want resumption like behavior. We
may also place the try block in a while loop that keeps re-entering the try block util the
result is satisfactory.

Nested try catch block in Java – Exception handling

When a try catch block is present in another try block then it is called the nested try catch
block. Each time a try block does not have a catch handler for a particular exception, then
the catch blocks of parent try block are inspected for that exception, if match is found that
that catch block executes.

If neither catch block nor parent catch block handles exception then the system generated
message would be shown for the exception, similar to what we see when we don’t handle
exception.

Lets see the syntax first then we will discuss this with an example.

112
Syntax of Nested try Catch

....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}

}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Nested Try Catch Example

Here we have deep (two level) nesting which means we have a try-catch block inside a
nested try block. To make you understand better I have given the names to each try block
in comments like try-block2, try-block3 etc.

This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside main
try-block, you can say that the main try-block is a grand parent of the try-block3. Refer the
explanation which is given at the end of this code.

class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2

113
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:

ArrayIndexOutOfBoundsException handled in main try-block


As you can see that the ArrayIndexOutOfBoundsException occurred in the grand child try-
block3. Since try-block3 is not handling this exception, the control then gets transferred to
the parent try-block2 and looked for the catch handlers in try-block2. Since the try-block2
is also not handling that exception, the control gets transferred to the main (grand parent)
try-block where it found the appropriate catch block for exception. This is how the the
nesting structure works.

114
Example 2: Nested try block

class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Output:

Inside block1
Exception: e1

115
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..

Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.

1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or
greater than the size of the string

Examples of Built-in Exception:

116
 Arithmetic exception

 Java

// Java program to demonstrate ArithmeticException


class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}

 Output:

Can't divide a number by 0


 NullPointer Exception

 Java

//Java program to demonstrate NullPointerException


class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

 Output:
NullPointerException..

117
 StringIndexOutOfBound Exception

 Java

// Java program to demonstrate


StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

 Output:

StringIndexOutOfBoundsException

 FileNotFound Exception

 Java

//Java program to demonstrate FileNotFoundException


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}

118
}
}

 Output:
File does not exist

 NumberFormat Exception

 Java

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

 Output:
Number format exception

 ArrayIndexOutOfBounds Exception

 Java

// Java program to demonstrate


ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}

119
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}

 Output:

Array Index is Out Of Bounds


User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, user can also create exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.

 The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a
subclass of it. This is done as:

class MyException extends Exception



 We can write a default constructor in his own exception class.

MyException(){}

 We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call super class(Exception)
constructor from this and send the string there.

MyException(String str)
{
super(str);
}

 To raise exception of user-defined type, we need to create an object to his exception
class and throw it using throw clause, as:

MyException me = new MyException(“Exception details”);


throw me;

120

 The following program illustrates how to create own exception class MyException.
 Details of account numbers, customer names, and balance amounts are taken in the
form of three arrays.
 In main() method, the details are displayed using a for-loop. At this time, check is
done if in any account the balance amount is less than the minimum balance amount
to be apt in the account.
 If it is so, then MyException is raised and a message is displayed “Balance amount is
less”.

 Java

// Java program to demonstrate user defined exception

// This program throws an exception whenever balance


// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};

private static String name[] =


{"Nish", "Shubh", "Sush", "Abhi", "Akash"};

private static double bal[] =


{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

// default constructor
MyException() { }

// parametrized constructor
MyException(String str) { super(str); }

// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");

// display the actual account information


for (int i = 0; i < 5 ; i++)

121
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);

// display own exception if balance < 1000


if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try

catch (MyException e) {
e.printStackTrace();
}
}
}

RunTime Error

MyException: Balance is less than 1000


at MyException.main(fileProperty.java:36)
Output:

ACCNO CUSTOMER BALANCE


1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
User defined Exception subclass in Java

Java provides rich set of built-in exception classes like: ArithmeticException, IOException,
NullPointerException etc. all are available in the java.lang package and used in exception
handling. These exceptions are already set to trigger on pre-defined conditions such as
when you divide a number by zero it triggers ArithmeticException.

Apart from these classes, Java allows us to create our own exception class to provide own
exception implementation. These type of exceptions are called user-defined exceptions
or custom exceptions.

122
You can create your own exception simply by extending java Exception class. You can
define a constructor for your Exception (not compulsory) and you can override
the toString() function to display your customized message on catch. Lets see an example.

Example: Custom Exception

In this example, we are creating an exception class MyException that extends the Java
Exception class and

class MyException extends Exception


{
private int ex;
MyException(int a)
{
ex = a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Demo
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception

123
}
}
}

output

MyException[-10] is less than zero

Example: Custom Exception

Lets take one more example to understand the custom exception. Here we created a class
ItemNotFound that extends the Exception class and helps to generate our own exception
implementation.

class ItemNotFound extends Exception


{
public ItemNotFound(String s) {
super(s);
}

class Demo
{
static void find(int arr[], int item) throws ItemNotFound
{
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
if(item == arr[i])
flag = true;
}
if(!flag)
{
throw new ItemNotFound("Item Not Found"); //calling constructor of user-defined
exception class
}
else
{
System.out.println("Item Found");
}
}

public static void main(String[] args)


{
try

124
{
find(new int[]{12,25,45}, 10);
}
catch(ItemNotFound i)
{
System.out.println(i);
}
}
}

Output

ItemNotFound: Item Not Found

multi-threaded

Java is a multi-threaded programming language which means we can develop multi-


threaded program using Java. A multi-threaded program contains two or more parts that
can run concurrently and each part can handle a different task at the same time making
optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS divides processing time
not only among different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.

Following are the stages of the life cycle −


125
 New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −

Step 1
As a first step, you need to implement a run() method provided by a Runnable interface.
This method provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of the run() method −
public void run( )

Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.

126
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method. Following is a simple syntax of start() method −
void start();

Example
Here is an example that creates a new thread and starts running it −
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

127
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
This will produce the following result −

Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that extends Thread class using
the following two simple steps. This approach provides more flexibility in handling
multiple threads created using available methods in Thread class.

Step 1
You will need to override run( ) method available in Thread class. This method provides
an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of run() method −
public void run( )

Step 2
Once Thread object is created, you can start it by calling start() method, which executes a
call to run( ) method. Following is a simple syntax of start() method −
void start( );

Example
Here is the preceding program rewritten to extend the Thread −
class ThreadDemo extends Thread {

128
private Thread t;
private String threadName;

ThreadDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();
}
}
This will produce the following result −

Output
Creating Thread-1
Starting Thread-1

129
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread Methods
Following is the list of important methods available in the Thread class.

Sr.No. Method & Description

1 public void start()


Starts the thread in a separate path of execution, then invokes the run() method on
this Thread object.

2 public void run()


If this Thread object was instantiated using a separate Runnable target, the run() method
is invoked on that Runnable object.

3 public final void setName(String name)


Changes the name of the Thread object. There is also a getName() method for retrieving
the name.

4 public final void setPriority(int priority)


Sets the priority of this Thread object. The possible values are between 1 and 10.

5 public final void setDaemon(boolean on)

130
A parameter of true denotes this Thread as a daemon thread.

6 public final void join(long millisec)


The current thread invokes this method on a second thread, causing the current
thread to block until the second thread terminates or the specified number of milliseconds
passes.

7 public void interrupt()


Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8 public final boolean isAlive()


Returns true if the thread is alive, which is any time after the thread has been started but
before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods
in the Thread class are static. Invoking one of the static methods performs the operation
on the currently running thread.

Sr.No. Method & Description

1 public static void yield()


Causes the currently running thread to yield to any other threads of the same priority that
are waiting to be scheduled.

2 public static void sleep(long millisec)


Causes the currently running thread to block for at least the specified number of milliseconds

3 public static boolean holdsLock(Object x)


Returns true if the current thread holds the lock on the given Object.

4 public static Thread currentThread()

131
Returns a reference to the currently running thread, which is the thread that invokes this
method.

5 public static void dumpStack()


Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.

Example
The following ThreadClassDemo program demonstrates some of these methods of the
Thread class. Consider a class DisplayMessage which implements Runnable −
// File Name : DisplayMessage.java
// Create a thread to implement Runnable

public class DisplayMessage implements Runnable {


private String message;

public DisplayMessage(String message) {


this.message = message;
}

public void run() {


while(true) {
System.out.println(message);
}
}
}
Following is another class which extends the Thread class −
// File Name : GuessANumber.java
// Create a thread to extentd Thread

public class GuessANumber extends Thread {


private int number;
public GuessANumber(int number) {
this.number = number;
}

public void run() {


int counter = 0;
int guess = 0;
do {

132
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}
Following is the main program, which makes use of the above-defined classes −
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {

public static void main(String [] args) {


Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}
This will produce the following result. You can try this example again and again and you
will get a different result every time.

133
Output
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

Thread Synchronization
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be closing
the same file.
So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread
can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources within
this block. Following is the general form of the synchronized statement −

Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents. Now we are going to see two
examples, where we will print a counter using two different threads. When threads are
not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in
sequence for both the threads.

134
Multithreading Example without Synchronization
Here is a simple example which may or may not print counter value in sequence and every
time we run it, it produces a different result based on CPU availability to a thread.

Example

class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {


private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {


threadName = name;
PD = pd;
}

public void run() {


PD.printCount();
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {


public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

135
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end


try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces a different result every time you run this program −

Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

Multithreading Example with Synchronization


Here is the same example which prints counter value in sequence and every time we run
it, it produces the same result.

Example
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {

136
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {


private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {


threadName = name;
PD = pd;
}

public void run() {


synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );


ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end


try {
T1.join();
T2.join();

137
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces the same result every time you run this program −

Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

inter thread communication

If you are aware of interprocess communication then it will be easy for you to understand
interthread communication. Interthread communication is important when you develop
an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication
possible. All the three methods are listed below −

Sr.No. Method & Description

1 public void wait()


Causes the current thread to wait until another thread invokes the notify().

2 public void notify()


Wakes up a single thread that is waiting on this object's monitor.

3 public void notifyAll()

138
Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are available in
all the classes. All three methods can be called only from within a synchronized context.

Example
This examples shows how two threads can communicate
using wait() and notify() method. You can create a complex system using the same
concept.
class Chat {
boolean flag = false;

public synchronized void Question(String msg) {


if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}

public synchronized void Answer(String msg) {


if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println(msg);
flag = false;
notify();
}
}

class T1 implements Runnable {


Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

139
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
}

public void run() {


for (int i = 0; i < s1.length; i++) {
m.Question(s1[i]);
}
}
}

class T2 implements Runnable {


Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

public T2(Chat m2) {


this.m = m2;
new Thread(this, "Answer").start();
}

public void run() {


for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
}
}
}
public class TestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Above example has been taken and then modified from
[https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]

140
Differences between thread-based multitasking and process-based multitasking,
Java

BASIS FOR
PROCESS THREAD
COMPARISON

Basic An executing program is called a A thread is a small part of a


process. process.

Address Space Every process has its separate All the threads of a process share
address space. the same address space
cooperatively as that of a
process.

Multitasking Process-based multitasking Thread-based multitasking


allows a computer to run two or allows a single program to run
more than two programs two or more threads
concurrently. concurrently.

Communication Communication between two Communication between two


processes is expensive and threads is less expensive as
limited. compared to process.

Switching Context switching from one Context switching from one


process to another process is thread to another thread is less
expensive. expensive as compared to
process.

Components A process has its own address A thread has its own register,
space, global variables, signal state, stack, program counter.
handlers, open files, child
processes, accounting
information.

Substitute Process are also called Thread are also called


heavyweight task. lightweight task.

141
BASIS FOR
PROCESS THREAD
COMPARISON

Control Process-based multitasking is not Thread-based multitasking is


under the control of Java. under the control of Java.

Example You are working on text editor it You are printing a file from text
refers to the execution of a editor while working on it that
process. resembles the execution of a
thread in the process.

UNIT – IV

The Collections Framework (java.util)

Collections in Java

The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

142
What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean It is used to insert the specified collection elements


addAll(Collection<? extends E>
c) in the invoking collection.

3 public boolean remove(Object It is used to delete an element from the collection.


element)

4 public boolean It is used to delete all the elements of the specified


removeAll(Collection<?> c)
collection from the invoking collection.

5 default boolean It is used to delete all the elements of the collection


removeIf(Predicate<? super E>
filter) that satisfy the specified predicate.

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c)
collection except the specified collection.

7 public int size() It returns the total number of elements in the collection.

8 public void clear() It removes the total number of elements from the

143
collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c)
collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime

type of the returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the collection


parallelStream()
as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as its

source.

17 default Spliterator<E> It generates a Spliterator over the specified elements in


spliterator()
the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the collection.

Collections in Java

1. Java Collection Framework

144
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate the gr

Java Collections can achieve all the operations that you perform on a data such as searching, sorting
deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Do You Know?
o What are the two ways to iterate the elements of a collection?
o What is the difference between ArrayList and LinkedList classes in collection framework?
o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection framework?
o What is the difference between HashMap and Hashtable class?
o What is the difference between Iterator and Enumeration interface in collection framework?
o How can we sort the elements of an object? What is the difference between Comparable and

Comparator interfaces?

o What does the hashcode() method?

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

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean It is used to insert the specified collection


addAll(Collection<? extends E>

146
c) elements in the invoking collection.

3 public boolean remove(Object It is used to delete an element from the


element)
collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c)
specified collection from the invoking collection.

5 default boolean It is used to delete all the elements of the


removeIf(Predicate<? super E>
filter) collection that satisfy the specified predicate.

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c)
collection except the specified collection.

7 public int size() It returns the total number of elements in

the collection.

8 public void clear() It removes the total number of elements from the

9 public boolean contains(Object It is used to search an element.


element)

1 public boolean It is used to search the specified collection in


0 containsAll(Collection<?> c)
the collection.

1 public Iterator iterator() It returns an iterator.


1

1 public Object[] toArray() It converts collection into array.


2

1 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
3

147
runtime type of the returned array is that of the

specified array.

1 public boolean isEmpty() It checks if collection is empty.


4

1 default Stream<E> It returns a possibly parallel Stream with the


5 parallelStream()
collection as its source.

1 default Stream<E> stream() It returns a sequential Stream with the collection


6

1 default Spliterator<E> It generates a Spliterator over the specified


7 spliterator()
elements in the collection.

1 public boolean equals(Object It matches two collections.


8 element)

1 public int hashCode() It returns the hash code number of the collection
9

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean hasNext() It returns true if the iterator has more elements othe

2 public Object next() It returns the element and moves the cursor pointer

148
3 public void remove() It removes the last elements returned by the iterator

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The Collection interface exte
therefore all the subclasses of Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the collection fra
that every collection will have. In other words, we can say that the Collection interface builds the fo
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collectio
implemented by all the subclasses of Collection interface.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure in whi
collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.

The classes that implement the List interface are given below.

149
ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order and
is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");

150
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ravi
Ajay

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection
framework.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ayush
Amit
Ashish
Garima

151
Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given
below.

152
PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj

153
Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Gautam
Karan
Ajay

Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate

154
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Vijay
Ravi
Ajay

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends


the HashSet class and implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements.

Consider the following example.

155
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");

156
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ajay
Ravi
Vijay

Map Interface in Java

The Map interface present in java.util package represents a mapping between a key and a
value. The Map interface is not a subtype of the Collection interface. Therefore it behaves
a bit differently from the rest of the collection types. A map contains unique keys.

Example:

// Java program to demonstrate

// the working of Map interface

import java.util.*;
class HashMapDemo {
public static void main(String args[])
{

157
Map<String, Integer> hm
= new HashMap<String, Integer>();

hm.put("a", new Integer(100));


hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));

// Traversing through the map


for (Map.Entry<String, Integer> me : hm.entrySet()) {
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}

Output:
a:100
b:200
c:300
d:400

Comparator Interface in Java with Examples


A comparator interface is used to order the objects of user-defined classes. A comparator
object is capable of comparing two objects of two different classes. Following function
compare obj1 with obj2
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no,
name, address, DOB, etc, and we need to sort the array based on Roll no or name?

Method 1: One obvious approach is to write our own sort() function using one of the
standard algorithms. This solution requires rewriting the whole sorting code for different
criteria like Roll No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects
of a user-defined class. This interface is present in java.util package and contains 2
methods compare(Object obj1, Object obj2) and equals(Object element). Using a
comparator, we can sort the elements based on data members. For instance, it may be on
roll no, name, age, or anything else.
Method of Collections class for sorting List elements is used to sort the elements of List by
the given comparator.

158
// To sort a given list. ComparatorClass must implement
// Comparator interface.
public void sort(List list, ComparatorClass c)
How does Collections.Sort() work?
Internally the Sort method does call Compare method of the classes it is sorting. To
compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to
say if it is less than, equal, or greater to the other. It uses this result to then determine if
they should be swapped for their sort.
Working Program:
Java

// Java program to demonstrate working of Comparator

// interface
import java.io.*;
import java.lang.*;
import java.util.*;

// A class to represent a student.


class Student {
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}

// Used to print student details in main()


public String toString()
{
return this.rollno + " " + this.name + " "
+ this.address;
}
}

class Sortbyroll implements Comparator<Student> {


// Used for sorting in ascending order of
// roll number

159
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}

class Sortbyname implements Comparator<Student> {


// Used for sorting in ascending order of
// name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}

// Driver class
class Main {
public static void main(String[] args)
{
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));

System.out.println("Unsorted");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));

Collections.sort(ar, new Sortbyroll());

System.out.println("\nSorted by rollno");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));

Collections.sort(ar, new Sortbyname());

System.out.println("\nSorted by name");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}

Output

Unsorted

160
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipur
By changing the return value inside the compare method, you can sort in any order that
you wish to. Eg. for descending order just change the positions of ‘a’ and ‘b’ in the above
compare method.
Sort collection by more than one field:
In previous articles, we have discussed how to sort the list of objects on the basis of a
single field using Comparable and Comparator interface But, what if we have a
requirement to sort ArrayList objects in accordance with more than one fields like firstly,
sort according to the student name and secondly, sort according to student age.
Below is the implementation of the above approach:

Java

// Java program to demonstrate working of Comparator

// interface more than one field

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Student {

161
// instance member variables
String Name;
int Age;

// parameterized constructor
public Student(String Name, Integer Age)
{
this.Name = Name;
this.Age = Age;
}

public String getName() { return Name; }

public void setName(String Name) { this.Name = Name; }

public Integer getAge() { return Age; }

public void setAge(Integer Age) { this.Age = Age; }

// overriding toString() method


@Override public String toString()
{
return "Customer{"
+ "Name=" + Name + ", Age=" + Age + '}';
}

static class CustomerSortingComparator


implements Comparator<Student> {

@Override
public int compare(Student customer1,
Student customer2)
{

// for comparison
int NameCompare = customer1.getName().compareTo(
customer2.getName());
int AgeCompare = customer1.getAge().compareTo(
customer2.getAge());

// 2-level comparison
return (NameCompare == 0) ? AgeCompare
: NameCompare;
}

162
}

public static void main(String[] args)


{

// create ArrayList to store Student


List<Student> al = new ArrayList<>();

// create customer objects using constructor


// initialization
Student obj1 = new Student("Ajay", 27);
Student obj2 = new Student("Sneha", 23);
Student obj3 = new Student("Simran", 37);
Student obj4 = new Student("Ajay", 22);
Student obj5 = new Student("Ajay", 29);
Student obj6 = new Student("Sneha", 22);

// add customer objects to ArrayList


al.add(obj1);
al.add(obj2);
al.add(obj3);
al.add(obj4);
al.add(obj5);
al.add(obj6);

// before Sorting arraylist: iterate using Iterator


Iterator<Student> custIterator = al.iterator();

System.out.println("Before Sorting:\n");
while (custIterator.hasNext()) {
System.out.println(custIterator.next());
}

// sorting using Collections.sort(al, comparator);


Collections.sort(al,
new CustomerSortingComparator());

// after Sorting arraylist: iterate using enhanced


// for-loop
System.out.println("\n\nAfter Sorting:\n");
for (Student customer : al) {
System.out.println(customer);
}
}

163
}

Output

Before Sorting:

Customer{Name=Ajay, Age=27}
Customer{Name=Sneha, Age=23}
Customer{Name=Simran, Age=37}
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=29}
Customer{Name=Sneha, Age=22}

After Sorting:

Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}

The Collection Algorithms


The collections framework defines several algorithms that can be applied to collections
and maps.
These algorithms are defined as static methods within the Collections class. Several of the
methods can throw a ClassCastException, which occurs when an attempt is made to
compare incompatible types, or an UnsupportedOperationException, which occurs
when an attempt is made to modify an unmodifiable collection.
The methods defined in collection framework's algorithm are summarized in the following
table −

164
Sr.No. Method & Description

1 static int binarySearch(List list, Object value, Comparator c)


Searches for value in the list ordered according to c. Returns the position of value in list,
or -1 if value is not found.

2 static int binarySearch(List list, Object value)


Searches for value in the list. The list must be sorted. Returns the position of value in list,
or -1 if value is not found.

3 static void copy(List list1, List list2)


Copies the elements of list2 to list1.

4 static Enumeration enumeration(Collection c)


Returns an enumeration over c.

5 static void fill(List list, Object obj)


Assigns obj to each element of the list.

6 static int indexOfSubList(List list, List subList)


Searches list for the first occurrence of subList. Returns the index of the first match, or .1
if no match is found.

7 static int lastIndexOfSubList(List list, List subList)


Searches list for the last occurrence of subList. Returns the index of the last match, or .
if no match is found.

8 static ArrayList list(Enumeration enum)


Returns an ArrayList that contains the elements of enum.

9 static Object max(Collection c, Comparator comp)

165
Returns the maximum element in c as determined by comp.

10 static Object max(Collection c)


Returns the maximum element in c as determined by natural ordering. The collection need
not be sorted.

11 static Object min(Collection c, Comparator comp)


Returns the minimum element in c as determined by comp. The collection need not be sorted.

12 static Object min(Collection c)


Returns the minimum element in c as determined by natural ordering.

13 static List nCopies(int num, Object obj)


Returns num copies of obj contained in an immutable list. num must be greater than or
equal to zero.

14 static boolean replaceAll(List list, Object old, Object new)


Replaces all occurrences of old with new in the list. Returns true if at least one replacement
occurred. Returns false, otherwise.

15 static void reverse(List list)


Reverses the sequence in list.

16 static Comparator reverseOrder( )


Returns a reverse comparator.

17 static void rotate(List list, int n)


Rotates list by n places to the right. To rotate left, use a negative value for n.

18 static void shuffle(List list, Random r)

166
Shuffles (i.e., randomizes) the elements in the list by using r as a source of random numbers.

19 static void shuffle(List list)


Shuffles (i.e., randomizes) the elements in list.

20 static Set singleton(Object obj)


Returns obj as an immutable set. This is an easy way to convert a single object into a set.

21 static List singletonList(Object obj)


Returns obj as an immutable list. This is an easy way to convert a single object into a list.

22 static Map singletonMap(Object k, Object v)


Returns the key/value pair k/v as an immutable map. This is an easy way to convert a single key

23 static void sort(List list, Comparator comp)


Sorts the elements of list as determined by comp.

24 static void sort(List list)


Sorts the elements of the list as determined by their natural ordering.

25 static void swap(List list, int idx1, int idx2)


Exchanges the elements in the list at the indices specified by idx1 and idx2.

26 static Collection synchronizedCollection(Collection c)


Returns a thread-safe collection backed by c.

27 static List synchronizedList(List list)


Returns a thread-safe list backed by list.

28 static Map synchronizedMap(Map m)

167
Returns a thread-safe map backed by m.

29 static Set synchronizedSet(Set s)


Returns a thread-safe set backed by s.

30 static SortedMap synchronizedSortedMap(SortedMap sm)


Returns a thread-safe sorted set backed by sm.

31 static SortedSet synchronizedSortedSet(SortedSet ss)


Returns a thread-safe set backed by ss.

32 static Collection unmodifiableCollection(Collection c)


Returns an unmodifiable collection backed by c.

33 static List unmodifiableList(List list)


Returns an unmodifiable list backed by the list.

34 static Map unmodifiableMap(Map m)


Returns an unmodifiable map backed by m.

35 static Set unmodifiableSet(Set s)


Returns an unmodifiable set backed by s.

36 static SortedMap unmodifiableSortedMap(SortedMap sm)


Returns an unmodifiable sorted map backed by sm.

37 static SortedSet unmodifiableSortedSet(SortedSet ss)


Returns an unmodifiable sorted set backed by ss.

168
Example
Following is an example, which demonstrates various algorithms.

import java.util.*;
public class AlgorithmsDemo {

public static void main(String args[]) {

// Create and initialize linked list


LinkedList ll = new LinkedList();
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));

// Create a reverse order comparator


Comparator r = Collections.reverseOrder();

// Sort list by using the comparator


Collections.sort(ll, r);

// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");

while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
Collections.shuffle(ll);

// display randomized list


li = ll.iterator();
System.out.print("List shuffled: ");

while(li.hasNext()) {
System.out.print(li.next() + " ");
}

System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}
This will produce the following result −

169
Output
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20

The Legacy Classes and Interfaces

Early version of java did not include the Collections framework. It only defined several
classes and interfaces that provide methods for storing objects. When Collections
framework were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes. All legacy classes and
interface were redesign by JDK 5 to support Generics. In general, the legacy classes are
supported because there is still some code that uses them.

The following are the legacy classes defined by java.util package

1. Dictionary

2. HashTable

3. Properties

4. Stack

5. Vector

There is only one legacy interface called Enumeration

NOTE: All the legacy classes are synchronized

Enumeration interface

1. Enumeration interface defines method to enumerate(obtain one at a time) through


collection of objects.

2. This interface is superseded(replaced) by Iterator interface.

3. However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.

4. It specifies the following two methods

boolean hasMoreElements() //It returns true while there are still more elements to
extract,

and returns false when all the elements have been enumerated.

170
Object nextElement() //It returns the next object in the enumeration i.e. each call to
nextElement() method

obtains the next object in the enumeration. It throws NoSuchElementException


when the

enumeration is complete.

Vector class

1. Vector is similar to ArrayList which represents a dynamic array.

2. There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy methods
that are not part of the Collections Framework.

3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is
fully compatible with collections, and a Vector can have its contents iterated by the
for-each loop.

4. Vector class has following four constructor

5. Vector() //This creates a default vector, which has an initial size of 10.

6.

7. Vector(int size) //This creates a vector whose initial capacity is specified by size.

8.

9. Vector(int size, int incr) //This creates a vector whose initial capacity is specified by
size and whose

10. increment is specified by incr. The increment specifies the number of elements to
allocate each time

11. when a vector is resized for addition of objects.

12.

Vector(Collection c) //This creates a vector that contains the elements of collection


c.

171
Vector defines several legacy methods. Lets see some important legacy methods defined
by Vector class.

Method Description

void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector

Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector<Integer> ve = new Vector<Integer>();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);

Enumeration<Integer> en = ve.elements();

while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}

172
}

10
20
30
40
50
60

Hashtable class

1. Like HashMap, Hashtable also stores key/value pair. However


neither keys nor values can be null.

2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.

3. Hashtable has following four constructor

4. Hashtable() //This is the default constructor. The default size is 11.

5. Hashtable(int size) //This creates a hash table that has an initial size specified by
size.

6. Hashtable(int size, float fillratio) //This creates a hash table that has an initial size
specified by size

7. and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full

8. the hash table can be before it is resized upward. Specifically, when the number of
elements is greater

9. than the capacity of the hash table multiplied by its fill ratio, the hash table is
expanded.

10. If you do not specify a fill ratio, then 0.75 is used.

173
11. Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is
initialized with the

12. elements in m. The capacity of the hash table is set to twice the number of elements
in m.

The default load factor of 0.75 is used.

Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable<String,Integer> ht = new Hashtable<String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));

Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}

a 100
b 200
c 300
d 400

Difference between HashMap and Hashtable

Hashtable HashMap

Hashtable class is synchronized. HashMap is not synchronized.

174
Because of Thread-safe, Hashtable is
HashMap works faster.
slower than HashMap

Neither key nor values can be null Both key and values can be null

Order of table remain constant over does not guarantee that order of map
time. will remain constant over time.

Properties class

1. Properties class extends Hashtable class.

2. It is used to maintain list of value in which both key and value are String

3. Properties class define two constructor

4. Properties() //This creates a Properties object that has no default values

5.

Properties(Properties propdefault) //This creates an object that uses propdefault


for its default values.

6. One advantage of Properties over Hashtable is that we can specify a default


property that will be useful when no value is associated with a certain key.

Note: In both cases, the property list is empty

7. In Properties class, you can specify a default property that will be returned if no
value is associated with a certain key.

175
Example of Properties class

import java.util.*;

public class Test


{

public static void main(String[] args)


{
Properties pr = new Properties();
pr.put("Java", "James Ghosling");
pr.put("C++", "Bjarne Stroustrup");
pr.put("C", "Dennis Ritchie");
pr.put("C#", "Microsoft Inc.");
Set< ?> creator = pr.keySet();

for(Object ob: creator)


{
System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );
}

Java was created by James Ghosling


C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc

Stack class

1. Stack class extends Vector.

2. It follows last-in, first-out principle for the stack elements.

3. It defines only one default constructor

Stack() //This creates an empty stack

4. If you want to put an object on the top of the stack, call push() method. If you want
to remove and return the top element, call pop() method. An EmptyStackException
is thrown if you call pop() method when the invoking stack is empty.

176
You can use peek() method to return, but not remove, the top object. The empty() method
returns true if nothing is on the stack. The search() method determines whether an object
exists on the stack and returns the number of pops that are required to bring it to the top of
the stack.

Example of Stack

import java.util.*;

class StackDemo {
public static void main(String args[]) {
Stack st = new Stack();
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();

while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");

st.pop();
st.pop();

System.out.println("\nAfter popping out two elements");

Enumeration e2 = st.elements();

while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");

}
}

11 22 33 44 55
After popping out two elements

11 22 33

Dictionary class

1. Dictionary is an abstract class.


177
2. It represents a key/value pair and operates much like Map.

3. Although it is not currently deprecated, Dictionary is classified as obsolete, because


it is fully superseded by Map class.

More Utility Classes


Utility class is a class that defines a set of methods that operates common, typically reused
functions. Majority of the utility classes define these common methods under static scope.
The Java Utility Package comprises of the collections framework, legacy collection classes,
event model, date and time facilities, internationalization, and miscellaneous utility classes
such as a string tokenizer, a random-number generator, and a bit array.

We already discussed about some of the utility classes in the earlier topic. In this section we
emphasize on String tokenizer class, time zone class, currency class etc. We’ll also discuss
about Formatter class which gives support for alignment as well as layout justification and
scanner class which enables a user to read values of various types. We’ll also explain what
java utility subpackages are.

The string tokenizer


The string tokenizer class allows an application to break a string into tokens.
The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted
strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at
creation time or on a per-token basis.

String Tokenizer Constructors:

Constructor Description

StringTokenizer(String str) Constructs a string tokenizer

StringTokenizer(String str, String delim) Constructs a string tokenizer

StringTokenizer(String str, String delim, boolean returnDelims) Constructs a string tokenizer

178
An instance of StringTokenizer behaves in one of two ways, depending on whether it was
created with the returnDelims flag having the value true or false:

 If the flag is false, delimiter characters serve to separate tokens. A token is a


maximal sequence of consecutive characters that are not delimiters.

 If the flag is true, delimiter characters are themselves considered to be tokens. A


token is thus either one delimiter character, or a maximal sequence of consecutive
characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be


tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.

String Tokenizer Methods:


Method Description

int countTokens() Calculates the number of times that this tokenizer's nextToken method ca
an exception.

boolean hasMoreElements() Returns the same value as the hasMoreTokens method.

boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.

Object nextElement() Returns the same value as the nextToken method, except that its declared
than String.

String nextToken() Returns the next token from this string tokenizer.

String nextToken(String Returns the next token in this string tokenizer's string.
delim)

StringTokenizer is a legacy class that is retained for compatibility reasons although its use
is discouraged in new code. It is recommended that anyone seeking this functionality use

179
the split method of String or the java.util.regex package instead.

String Tokenizer Demo

CODE

import java.util.StringTokenizer;

class StringTokenizerDemo
{
public static void main(String arg[])
{
StringTokenizer st1 = new StringTokenizer("Welcome to Merit" +
" Campus."); // LINE A
while (st1.hasMoreTokens()) {
System.out.println(st1.nextToken());
}
System.out.print("---------\n");
StringTokenizer st2 = new StringTokenizer("It's an,Education," +
"Website.", ","); // LINE B
while (st2.hasMoreTokens()) {
System.out.println(st2.nextToken());
}
System.out.print("---------\n");
StringTokenizer st3 = new StringTokenizer("Learn~programming~with Java.",
"~", true); // LINE C
while (st3.hasMoreTokens()) {
System.out.println(st3.nextToken());
}
}
}
OUTPUT

Welcome
to
Merit
Campus.
---------
It's an
Education
Website.
---------
Learn
~
programming

180
~
with Java.

BitSet
The BitSet class creates a special type of array that holds bit values. This array can increase
in size as needed. This makes it similar to a vector of bits. The bits of a BitSet are indexed
by nonnegative integers. Individual indexed bits can be examined, set, or cleared.
One BitSet may be used to modify the contents of another BitSet through logical AND,
logical inclusive OR, and logical exclusive OR operations.

Constructors :
BitSet class has two constructors:

Constructor Description

BitSet() Creates a default object

BitSet( int size ) Allows us to specify the initial size i.e. the no. of bits that the BitSet can hold

NOTE:
By default, all bits are initialized to zero.

Some Important Methods :

Method Description

Object clone() Creates a copy of the invoking BitSet object.

void set( int index ) Sets the bit specified by index.

void set( int index, boolean v ) Sets the bit specified by index to the value passed in v. true sets t

void or( BitSet bitSet ) ORs the contents of the invoking BitSet object with that specified
into the invoking object.

181
void and( BitSet bitSet ) ANDs the contents of the invoking BitSet object with that specifi
result into the invoking object

void andNot( BitSet bitSet ) For each 1 bit in bitSet, the corresponding bit in the invoking Bit

void xor( BitSet bitSet ) XORs the contents of the invoking BitSet object with that specifie
result into the invoking object

void set( int startIndex, int endIndex ) Sets the bits from startIndex to (endIndex – 1)

void set( int startIndex, int endIndex, Sets the bits from startIndex to (endIndex – 1) to the value passe
boolean v ) false clears the bits

void flip(int index) Reverse the bit specified by index.

void flip(int startIndex, int endIndex) Reverse the bits from startIndex to endIndex-1

BitSetDemo

CODE

class BitSetDemo
{
public static void main(String arg[])
{
BitSet bitSetA = new BitSet();
bitSetA.set(2);
bitSetA.set(3);
bitSetA.set(4);
bitSetA.set(5);
System.out.println("bitSetA = " + bitSetA);
BitSet bitSetB = new BitSet();
bitSetB.set(1, 5);
System.out.println("bitSetB = " + bitSetB);
// Clone of bitSetA
BitSet bitSetC = new BitSet();
bitSetC = (BitSet) bitSetA.clone();
System.out.println("bitSetC = " + bitSetC);
// AND bits

182
bitSetA.and(bitSetB);
System.out.println("bitSetA and bitSetB = " + bitSetA);
// OR bits
bitSetA.or(bitSetB);
System.out.println("bitSetA or bitSetB = " + bitSetA);
// AND NOT
bitSetA.andNot(bitSetB);
System.out.println("bitSetA and not bitSetB = " + bitSetA);
// XOR bits
bitSetC.xor(bitSetB);
System.out.println("bitSetC xor bitSetB = " + bitSetC);
}
}
OUTPUT

bitSetA = {2, 3, 4, 5}
bitSetB = {1, 2, 3, 4}
bitSetC = {2, 3, 4, 5}
bitSetA and bitSetB = {2, 3, 4}
bitSetA or bitSetB = {1, 2, 3, 4}
bitSetA and not bitSetB = {}
bitSetC xor bitSetB = {1, 5}
Date
Date class is available in java.util package, it represents a specific instant of time, with
millisecond precision. Date allows the interpretation of dates as year, month, day, hour,
minute, and second values. It also allows the formatting and parsing of date strings.

Date Constructors:

Constructor Description

Date() Allocates a Date object and initializes it so that it represents the time at which it was allo
millisecond.

Date(long Allocates a Date object and initializes it to represent the specified number of millisecond
date) known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Date Methods:

183
Method Description

boolean after(Date date) Tests if this date is after the specified date.

boolean before(Date Tests if this date is before the specified date.


date)

Object clone() Return a copy of this object.

int compareTo(Date date) Compares two dates for ordering.

boolean equals(Object Compares two dates for equality.


date)

long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

represented by this Date object.

int hashCode() Returns a hash code value for this object.

void setTime(long time) Sets this Date object to represent a point in time that is time milliseconds

after January 1, 1970 00:00:00 GMT.

String toString() Converts this Date object to a String.

Simple Date Format Codes:

Character Description Example

y Year in four digits 2013

184
M Month in a year July or 07

d Day in a month 10

h Hour in A.M./P.M. (1~12) 12

H Hour in day (0~23) 22

m Minute in hour 30

s Second in minute 56

S Millisecond 234

E Day in week Friday

D Day in year 364

F Day of week in month 2 (second Wed. in July)

w Week in year 40

W Week in month 1

a A.M./P.M. marker PM

k Hour in day (1~24) 23

K Hour in A.M./P.M. (0~11) 10

185
z Time zone Eastern Standard Time

' Escape for text Delimiter

" Single quote '

G Era designator AD

Date Example

CODE

import java.util.*;

class DateExampleTest
{
public static void main(String arg[])
{
try
{
// Get current date and time
Date date = new Date(); // LINE A
System.out.println(date);
// Convert Date to String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
// LINE B
String stringDate = dateFormat.format(date); // LINE C
System.out.println(stringDate);
// Convert String to Date.
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateInString = "15/08/1947 02:25:56";
date = df.parse(dateInString); // LINE D
System.out.println(date);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT

186
Fri Apr 18 14:25:43 IST 2014
18/04/2014 02:25:43
Fri Aug 15 02:25:56 IST 1947

Calender
Calender is an abstract class. It provides a set of methods to manipulate the date and time. The
subclass of calender class provides the specific implementation to the abstract methods defined
by calender to meet their own requirements.

For example Java GregorianCalendar is a subclass of calender class. The calender class does not
define its constructor. Therefore an object of an abstract calender class can’t be created.
The calender defines several methods. some commonly used methods are as follows:

Calender Methods:

Method Description

static Calender getInstance() This method returns the object of calender class for the default location

Int get(int const) This method returns the value of the requested

component of the invoking object. This component is

specified be ‘const’. It can be any one of the integer constants. For exam
Calender.HOUR etc.

Void set(int const,int value) This method sets the value of the date or time component specified by c
constant defined by calender class. For example Calender.HOUR

final void set(int year, int month, int Sets various date and time components of the invoking object.
dayOfMonth)

final void set(int year, int month, int Sets various date and time components of the invoking object.
dayOfMonth, int hours, int minutes)

187
final void set(int year, int month, int Sets various date and time components of the invoking object.
dayOfMonth, int hours, int minutes, int
seconds)

TimeZonegetTimeZone() These methods get and set the time zone for the invoking object.
Void setTimeZone(TimeZone+zObj) of setTimeZone() method specifies the TimeZone object to be set.

Boolean equals(Object calObj) This method returns true if both the invoking calender object and the o
Otherwise returns false.

Boolean after(Object calObj) This method returns true if the invoking calender object contains a date
specified by calObj object. Otherwise returns false.

Boolean before(Object calObj) This method returns true if the invoking calender object contains a date
specified by calObj object. Otherwise returns false.

Calendar defines the following int constants, which are used when you get or set components of the
calendar:

ALL_STYLES FRIDAY

AM HOUR

AM_PM HOUR_OF_DAY

APRIL JANUARY

AUGUST JULY

DATE JUNE

DAY_OF_MONTH LONG

188
DAY_OF_WEEK MARCH

DAY_OF_WEEK_IN_MONTH MAY

DAY_OF_YEAR MILLISECOND

DECEMBER MINUTE

DST_OFFSET MONDAY

ERA MONTH

FEBRUARY NOVEMBER

FIELD_COUNT OCTOBER

DateAndTime

CODE

import java.util.Calendar;

class ExampleOfDateAndTime
{
public static void main(String arg[])
{
String months[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT",
"NOV", "DEC"};

/*Create a calendar initialized with the


current date and time in the default
locale and timezone.*/
Calendar cal = Calendar.getInstance();

//Display current time and date information.


System.out.println("Date :");
System.out.print(months[cal.get(java.util.Calendar.MONTH)]);
System.out.print(" " + cal.get(Calendar.DATE) + " ");// LINE D
System.out.println(cal.get(Calendar.YEAR));

189
System.out.println("Current Time: "); // LINE A
System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.println(cal.get(Calendar.SECOND));

//Set the time and date information and display it.


cal.set(Calendar.HOUR, 10); // LINE C
cal.set(Calendar.MINUTE, 29); // LINE C
cal.set(Calendar.SECOND, 22); // LINE C

System.out.println("Updated time"); // LINE B


System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.println(cal.get(Calendar.SECOND));

}
}
OUTPUT

Date :
APR 9 2014
Current Time:
7:40:20
Updated time
10:29:22

Random

java.util.Random instance is used to generate a stream of pseudo-random numbers.

Random Constructors:

Constructor Description

Random() Creates a new random number generator.

Random(long seed) Creates a new random number generator using a single long seed.

Random Methods:

190
Method Description

protected int next(int Generates the next pseudorandom number.


bits)

boolean nextBoolean() Returns the next pseudorandom, uniformly distributed boolean value from this
sequence.

void nextBytes(byte[] Generates random bytes and places them into a user-supplied byte array.
bytes)

double nextDouble() Returns the next pseudorandom, uniformly distributed double value between

0.0 and 1.0 from this random number generator's sequence.

float nextFloat() Returns the next pseudorandom, uniformly distributed float value between

0.0 and 1.0 from this random number generator's sequence.

double nextGaussian() Returns the next pseudorandom, Gaussian ("normally") distributed double

value with mean 0.0 and standard deviation 1.0 from this random number

generator's sequence.

int nextInt() Returns the next pseudorandom, uniformly distributed int value from this

random number generator's sequence.

int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive
value n (exclusive), drawn from this random number generator's sequence.

long nextLong() Returns the next pseudorandom, uniformly distributed long value from this

191
random number generator's sequence.

void setSeed(long Sets the seed of this random number generator using a single long seed.
seed)

Random

CODE

import java.util.Random;

class RandomTest
{
public static void main(String arg[])
{
Random r = new Random();

System.out.println("The next Integer value : " + r.nextInt()); // LINE A


System.out.println("The next Boolean value : " + r.nextBoolean());

byte[] b = new byte[30];


r.nextBytes(b); // Puts the next byte in array
System.out.println("Value of Byte array : " + b);

System.out.println("The next Double value : " + r.nextDouble());


System.out.println("The next Float value : " + r.nextFloat());
System.out.println("The next Gaussian value : " + r.nextGaussian());
System.out.println("The next Integer value between 0 to 4 : " + r.nextInt(5));
System.out.println("The next Long value : " + r.nextLong());
r.setSeed(20);
System.out.println("The set Seed value : " + r.nextInt());

}
}
OUTPUT

The next Integer value : 1129872169


The next Boolean value : true
Value of Byte array : [B@103074e
The next Double value : 0.47766930003831065
The next Float value : 0.13917398
The next Gaussian value : 0.8715938816913958

192
The next Integer value between 0 to 4 : 1
The next Long value : 3604397887200514771
The set Seed value : -1150867590

Formatter
Formatter class in java.util package helps in formatting the display numbers, string, time
and date in any format you like. For e.g., we could write the
amount 123456.7 as 1,23,456.7 or 123,456.7 or 123456.70 or 123.456,70 depending upon
the requirement. The Formatter class helps in displaying them in required format.

Initially we will discuss various ways for creating the Formatter objects. Some of the
constructors are

/*1*/ Formatter()
/*2*/ Formatter(Appendable buf)
/*3*/ Formatter(Appendable buf, Locale loc)
/*4*/ Formatter(String filename) throws FileNotFoundException
/*5*/ Formatter(String filename, String charset) throws FileNotFoundException, Unsuppor
tedEncodingException
/*6*/ Formatter(File outF) throws FileNotFoundException
/*7*/ Formatter(OutputStream outStream)

The most commonly used constructor is the first one and by default any data formatted
using this type of Formatter, will be written to StringBuilder and using the default Locale.
The output of the Formatter can be accessed using out() method.
If we want to the output to be written to our own StringBuilder then we can use the
constructor 2 and 3. If we want to write to file or OutputStream we can use the other
constructors. We can also pass the Locale and charset as required.

In Java Formatter Methods we will discuss about various methods in the Formatter class.

Scanner

The Scanner class is a class in java.util package, which allows a user to read values of
various types.
The Scanner looks for tokens in the input. A token is a series of characters that ends with
whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the
end of the file.
For example, if we read a line that has a series of numbers separated by blanks, the scanner
will take each number as a separate token.

193
Constructors
Scanner class has several constructors. Among them, the following are particularly useful.

Constructor Description

Scanner(File source) Constructs a new scanner that produces values scanned from the

specified file. If the source file is not found, a FileNotFoundException is thrown. S


must be caught or forwarded by putting the phrase “throws FileNotFoundExcept

Scanner(InputStream Constructs a new Scanner that produces values scanned from the
source)
specified input stream.

Scanner(String Constructs a new scanner that produces values scanned from the
source)
specified string.

Let's now see different ways of instantiating a Scanner object.

Instantiating a Scanner object by passing a File object as parameter

CODE

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class ScannerConstructorDemo1
{
public static void main(String arg[])
{
// Read from a file rather than the keyboard
Scanner sc = new Scanner(new File("FIFA14.txt")); // LINE A

// Check if sc has another token in the file


while(sc.hasNext())
System.out.println(sc.next());

// Close the scanner


sc.close();
}

194
}
OUTPUT

Germany
Argentina
Netherlands
Brazil
Colombia
France
Costa-Rica
Belgium

UNIT - V

GUI Programming with Swing

What is Swing in Java?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components.
Swing provides a rich set of widgets and packages to make sophisticated GUI components
for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for
Java programs that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java GUI programming components like
button, textbox, etc. from the library and do not have to create the components from
scratch.

What is GUI in Java?

GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications. It is mainly made of graphical components like buttons, labels, windows, etc.
through which the user can interact with an application. GUI plays an important role to
build easy interfaces for Java applications.

195
Java GUI Example

Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples.

Example: To learn Java GUI programming in this Java GUI tutorial


Step 1) Copy the following code into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}
}

Step 2) Save, Compile, and Run the code.


Step 3) Now let's Add a Button to our frame. Copy following code into an editor from given
Java GUI Example

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}

Step 4) Execute the code. You will get a big button

196
Step 5) How about adding two buttons? Copy the following code into an editor.

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}

Step 6) Save , Compile , and Run the program.


Step 7) Unexpected output =? Buttons are getting overlapped.

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.

197
Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1 AWT components are platform- Java swing components


) dependent. are platform-independent.

2 AWT components are heavyweight. Swing components


) are lightweight.

3 AWT doesn't support pluggable look and Swing supports pluggable look
) feel. and feel.

4 AWT provides less components than Swing provides more powerful


) Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5 AWT doesn't follows MVC(Model View Swing follows MVC.


) Controller) where model represents data,
view represents presentation and
controller acts as an interface between
model and view.

What is MVC Architecture in Java?


Model designs based on MVC architecture follow the MVC design pattern and they separate
the application logic from the user interface when designing software. As the name implies
MVC pattern has three layers, which are:

 Model – Represents the business layer of the application


 View – Defines the presentation of the application
 Controller – Manages the flow of the application

198
In Java Programming context, the Model consists of simple Java classes, the View displays
the data and the Controller consists of servlets. This separation results in user requests
being processed as follows:

1. The browser on the client sends a request for a page to the controller present on the
server
2. The controller performs the action of invoking the model, thereby, retrieving the
data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display

Separating a software application into these three distinct components is a good idea for a
number of reasons. Let’s take a look at what those are.

Java Certification Training Course

 Instructor-led Sessions
 Real-life Case Studies
 Assignments
 Lifetime Access

Advantages of MVC Architecture in Java


MVC architecture offers a lot of advantages for a programmer when developing
applications, which include:

 Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
 Offers improved scalability, that supplements the ability of the application to grow
 As components have a low dependency on each other, they are easy to maintain
 A model can be reused by multiple views which provides reusability of code
 Adoption of MVC makes an application more expressive and easy to understand

199
 Extending and testing of the application becomes easy

Now you know why the MVC is the most popular design patterns in the web programming
world. But, if you are still struggling to get your head around the concept of MVC, don’t
worry. We will dig deep into each of these layers and learn their purpose with the help of
an example program.

Implementation of MVC using Java


To implement a web application based on MVC design pattern, we will create

 Course Class, which acts as the model layer


 CourseView Class, which defines the presentation layer (view layer)
 CourseContoller Class, which acts as a controller

Now, let’s explore these layers one by one.

The Model Layer


In the MVC design pattern, the model is the data layer which defines the business logic of
the system and also represents the state of the application. The model objects retrieve and
store the state of the model in a database. Through this layer, we apply rules to data, which
eventually represents the concepts our application manages. Now, let’s create a model
using Course Class.

1 package MyPackage;
2
3 public class Course {
4 private String CourseName;
5 private String CourseId;
6 private String CourseCategory;
7
8 public String getId() {
9 return CourseId;
10 }
11
12 public void setId(String id) {
13 this.CourseId = id;
14 }
15
16 public String getName() {
17 return CourseName;
18 }
19
20 public void setName(String name) {
21 this.CourseName = name;
22 }
23

200
24 public String getCategory() {
25 return CourseCategory;
26 }
27
28 public void setCategory(String category) {
29 this.CourseCategory = category;
30 }
31
32 }
The code is easy to understand and is self-explanatory. It consists of functions to get/set
course details.
The View Layer
This layer of the MVC design pattern represents the output of the application or the user
interface. It displays the data fetched from the model layer by the controller and presents
the data to the user whenever asked for. It receives all the information it needs from the
controller and it doesn’t need to interact with the business layer directly. Let’s create a
view using CourseView Class.

package MyPackage;

public class CourseView {

public void printCourseDetails(String CourseName, String CourseId, String CourseCategory){

System.out.println("Course Details: ");

System.out.println("Name: " + CourseName);

System.out.println("Course ID: " + CourseId);

System.out.println("Course Category: " + CourseCategory);

This code is simply to print the values to the console. Next up we have the controller of the
web application.

Programming & Frameworks Training

The Controller Layer


The Controller is like an interface between Model and View. It receives the user requests
from the view layer and processes them, including the necessary validations. The requests
are then sent to model for data processing. Once they are processed, the data is again sent

201
back to the controller and then displayed on the view. Let’s create CourseContoller
Class which acts as a controller.

1
package MyPackage;
2
public class CourseController {
3 private Course model;
4 private CourseView view;

5 public CourseController(Course model, CourseView view){


this.model = model;
6 this.view = view;
}
7

8 public void setCourseName(String name){


model.setName(name);
9 }
10 public String getCourseName(){
return model.getName();
11
}
12
public void setCourseId(String id){
13 model.setId(id);
}
14

15 public String getCourseId(){


return model.getId();
16 }

17 public void setCourseCategory(String category){


model.setCategory(category);
18
}
19
public String getCourseCategory(){
20 return model.getCategory();
}
21 public void updateView(){
view.printCourseDetails(model.getName(), model.getId(), model.getCategory());
22
}
}

A cursory glance at the code will tell us that this controller class is just responsible for
calling the model to get/set the data and updating the view based on that. Now let’s have a
look at how all of these are tied together.

202
Main Java Class
Let’s call this class “MVCPatternDemo.java”. Check out the code below.

1 package MyPackage;
2
3 public class MVCPatternDemo {
4 public static void main(String[] args) {
5
6 //fetch student record based on his roll no from the database
7 Course model = retriveCourseFromDatabase();
8
9 //Create a view : to write course details on console
10 CourseView view = new CourseView();
11
12 CourseController controller = new CourseController(model, view);
13
14 controller.updateView();
15
16 //update model data
17 controller.setCourseName("Python");
18 System.out.println("nAfter updating, Course Details are as follows");
19
20 controller.updateView();
21 }
22
23 private static Course retriveCourseFromDatabase(){
24 Course course = new Course();
25 course.setName("Java");
26 course.setId("01");
27 course.setCategory("Programming");
28 return course;
29 }
30 }
The above class fetches the course data from the function using which user enters the set of
values. It then pushes those values into the Course model. Then, it initializes the view we
had created earlier in the article. Further, it also invokes the CourseController class and
binds it to the Course class and the CourseView class. The updateView() method which is a
part of the controller then updates the course details on the console. Check out the output
below.
Output

1 Course Details:

2 Name: Java

203
3 Course ID: 01
4 Course Category: Programming
5

6 After updating, Course Details are as follows

7 Course Details:

8 Name: Python

9 Course ID: 01

10 Course Category: Programming

What is a LayoutManager and types of LayoutManager in Java?


The Layout managers enable us to control the way in which visual components are
arranged in the GUI forms by determining the size and position of components within the
containers.
Types of LayoutManager
There are 6 layout managers in Java

 FlowLayout: It arranges the components in a container like the words on a page. It


fills the top line from left to right and top to bottom. The components are
arranged in the order as they are added i.e. first components appears at top left, if
the container is not wide enough to display all the components, it is wrapped
around the line. Vertical and horizontal gap between components can be controlled.
The components can be left, center or right aligned.
 BorderLayout: It arranges all the components along the edges or the middle of the
container i.e. top, bottom, right and left edges of the area. The components added
to the top or bottom gets its preferred height, but its width will be the width of the
container and also the components added to the left or right gets its preferred
width, but its height will be the remaining height of the container. The components
added to the center gets neither its preferred height or width. It covers the
remaining area of the container.
 GridLayout: It arranges all the components in a grid of equally sized cells, adding
them from the left to right and top to bottom. Only one component can be placed
in a cell and each region of the grid will have the same size. When the container is
resized, all cells are automatically resized. The order of placing the components in a
cell is determined as they were added.
 GridBagLayout: It is a powerful layout which arranges all the components in a grid
of cells and maintains the aspect ration of the object whenever the container is
resized. In this layout, cells may be different in size. It assigns a consistent
horizontal and vertical gap among components. It allows us to specify a default
alignment for components within the columns or rows.

204
 BoxLayout: It arranges multiple components in either vertically or horizontally,
but not both. The components are arranged from left to right or top to bottom. If
the components are aligned horizontally, the height of all components will be the
same and equal to the largest sized components. If the components are
aligned vertically, the width of all components will be the same and equal to the
largest width components.
 CardLayout: It arranges two or more components having the same size. The
components are arranged in a deck, where all the cards of the same size and
the only top card are visible at any time. The first component added in the
container will be kept at the top of the deck. The default gap at the left, right, top and
bottom edges are zero and the card components are displayed either horizontally
or vertically.
Example

import java.awt.*;

import javax.swing.*;

public class LayoutManagerTest extends JFrame {

JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1, gridLayoutPanel2,


gridLayoutPanel3;

JButton one, two, three, four, five, six;

JLabel bottom, lbl1, lbl2, lbl3;

public LayoutManagerTest() {

setTitle("LayoutManager Test");

setLayout(new BorderLayout()); // Set BorderLayout for JFrame

flowLayoutPanel1 = new JPanel();

one = new JButton("One");

two = new JButton("Two");

three = new JButton("Three");

flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); // Set


FlowLayout Manager

flowLayoutPanel1.add(one);

flowLayoutPanel1.add(two);

205
flowLayoutPanel1.add(three);

flowLayoutPanel2 = new JPanel();

bottom = new JLabel("This is South");

flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)); // Set


FlowLayout Manager

flowLayoutPanel2.add(bottom);

gridLayoutPanel1 = new JPanel();

gridLayoutPanel2 = new JPanel();

gridLayoutPanel3 = new JPanel();

lbl1 = new JLabel("One");

lbl2 = new JLabel("Two");

lbl3 = new JLabel("Three");

four = new JButton("Four");

five = new JButton("Five");

six = new JButton("Six");

gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set GridLayout Manager

gridLayoutPanel2.add(lbl1);

gridLayoutPanel2.add(lbl2);

gridLayoutPanel2.add(lbl3);

gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set GridLayout Manager

gridLayoutPanel3.add(four);

gridLayoutPanel3.add(five);

gridLayoutPanel3.add(six);

gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout Manager

gridLayoutPanel1.add(gridLayoutPanel2);

gridLayoutPanel1.add(gridLayoutPanel3);

206
add(flowLayoutPanel1, BorderLayout.NORTH);

add(flowLayoutPanel2, BorderLayout.SOUTH);

add(gridLayoutPanel1, BorderLayout.CENTER);

setSize(400, 325);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

setVisible(true);

public static void main(String args[]) {

new LayoutManagerTest();

}
Output

SWING - Event Handling


In this chapter, you will learn about Events, its types, and also learn how to handle an
event. Example is provided at the end of the chapter for better understanding.

What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change in the
state of the source. Events are generated as a result of user interaction with the graphical

207
user interface components. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from the list, and scrolling the page are
the activities that causes an event to occur.

Types of Event
The events can be broadly classified into two categories −
 Foreground Events − These events require direct interaction of the user. They are
generated as consequences of a person interacting with the graphical components
in the Graphical User Interface. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from list, scrolling
the page, etc.
 Background Events − These events require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer expiration, and
operation completion are some examples of background events.

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs. This mechanism has a code which is known as an event handler, that is
executed when an event occurs.
Java uses the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants.
 Source − The source is an object on which the event occurs. Source is responsible
for providing information of the occurred event to it's handler. Java provide us with
classes for the source object.
 Listener − It is also known as event handler. The listener is responsible for
generating a response to an event. From the point of view of Java implementation,
the listener is also an object. The listener waits till it receives an event. Once the
event is received, the listener processes the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from
the logic that generates the event. The user interface element is able to delegate the
processing of an event to a separate piece of code.
In this model, the listener needs to be registered with the source object so that the listener
can receive the event notification. This is an efficient way of handling the event because
the event notifications are sent only to those listeners who want to receive them.

Steps Involved in Event Handling


Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and information
about the source and the event get populated within the same object.
Step 3 − Event object is forwarded to the method of the registered listener class.

208
Step 4 − The method is gets executed and returns.

Points to Remember About the Listener


 In order to design a listener class, you have to develop some listener interfaces.
These Listener interfaces forecast some public abstract callback methods, which
must be implemented by the listener class.
 If you do not implement any of the predefined interfaces, then your class cannot act
as a listener class for a source object.

Callback Methods
These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represent an event method. In response to an event, java jre will fire callback
method. All such callback methods are provided in listener interfaces.
If a component wants some listener to listen ot its events, the source must register itself to
the listener.

Event Handling Example


Create the following Java program using any editor of your choice in say D:/ > SWING >
com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingControlDemo {


private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;

public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));

209
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");

JButton okButton = new JButton("OK");


JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");

okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);

mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if( command.equals( "OK" )) {


statusLabel.setText("Ok Button clicked.");
} else if( command.equals( "Submit" ) ) {

210
statusLabel.setText("Submit Button clicked.");
} else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the
following command.
D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the
following command.
D:\AWT>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.

Delegation Event Model in Java

The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts
with the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code
to respond to functionality to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation
event model in Java. We will also discuss the different components of an Event Model.

211
Event Processing in Java

Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the
AWT was based on inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or handleEvent() methods. The below
image demonstrates the event processing.

But, the modern approach for event processing is based on the Delegation Model. It defines
a standard and compatible mechanism to generate and process events. In this model, a
source generates an event and forwards it to one or more listeners. The listener waits until
it receives an event. Once it receives the event, it is processed by the listener and returns it.
The UI elements are able to delegate the processing of an event to a separate function.

The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.

In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them. So, this approach is more convenient than the inheritance-based event model (in Java
1.0).

In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took
lots of time. The Delegation Event model overcame this issue.

Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

Events

The Events are the objects that define state change in a source. An event can be generated
as a reaction of a user while interacting with GUI elements. Some of the event generation
activities are moving the mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many other user operations
as events.

212
The Events may also occur that may be not related to user interaction, such as a timer
expires, counter exceeded, system failures, or a task is completed, etc. We can define events
for any of the applied actions.

Event Sources

A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several different
types of events.

A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all
the events will be notified to registered listeners and receive the event object. This process
is known as event multicasting. In few cases, the event notification will only be sent to
listeners that register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersExcepti


on

From the above syntax, the Type is the name of the event, and e2 is the event listener's
reference. When the specified event occurs, it will be notified to the registered listener.
This process is known as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener
if not needed. Below is an example of the method that will remove the event from the
listener.

1. public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the reference of the listener.
For example, to remove the keyboard listener, the removeKeyListener() method will be
called.

The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of
events, such as adding or removing them from the listener.

213
Event Listeners

An event listener is an object that is invoked when an event triggers. The listeners require
two things; first, it must be registered with a source; however, it can be registered with
several resources to receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These interfaces
can be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse
is dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.

Types of Events

The events are categories into the following two categories:

The Foreground Events:

The foreground events are those events that require direct interaction of the user. These
types of events are generated as a result of user interaction with the GUI component. For
example, clicking on a button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.

The Background Events :

The Background events are those events that result from the interaction of the end-user.
For example, an Operating system interrupts system failure (Hardware or Software).

To handle these events, we need an event handling mechanism that provides control over
the events and responses.

The Delegation Model

The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based
event model using AWT to resolve the event problems. It provides a convenient mechanism
to support complex Java programs.

Design Goals

The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.

214
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.

Let's implement it with an example:

Java Program to Implement the Event Deligation Model

The below is a Java program to handle events implementing the event deligation model:

TestApp.java:

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18. }
19.
20. class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }

215
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
49. Command searchCmd = new Command(Command.SEARCH, app);
50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }

Output:

216
Searching...

java Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods
of listener interfaces. So it saves code.

The adapter classes are found


in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter classes
with their corresponding listener interfaces are given below.

java.awt.event Adapter classes


Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes


Adapter class Listener interface

DragSourceAdapter DragSourceListener

217
DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes


Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class AdapterExample{
4. Frame f;
5. AdapterExample(){
6. f=new Frame("Window Adapter");
7. f.addWindowListener(new WindowAdapter(){
8. public void windowClosing(WindowEvent e) {
9. f.dispose();
10. }
11. });
12.
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new AdapterExample();
19. }
20. }

Output:

218
Java MouseAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseAdapterExample extends MouseAdapter{
4. Frame f;
5. MouseAdapterExample(){
6. f=new Frame("Mouse Adapter");
7. f.addMouseListener(this);
8.
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public void mouseClicked(MouseEvent e) {
14. Graphics g=f.getGraphics();
15. g.setColor(Color.BLUE);
16. g.fillOval(e.getX(),e.getY(),30,30);
17. }
18.
19. public static void main(String[] args) {
20. new MouseAdapterExample();
21. }
22. }

Output:

Java Inner Classes

1. Java Inner classes


2. Advantage of Inner class
3. Difference between nested class and inner class

219
4. Types of Nested classes

Java inner class or nested class is a class which is 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. }

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

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(){

220
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }

Output:

nice fruits

A Simple Swing Application, Applets

Applet Definition:

 Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart of a
web document.
 After a user receives an applet, the applet can produce a graphical user interface. It
has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
 Any applet in Java is a class that extends the java.applet.Applet class.
 An Applet class does not have any main() method. It is viewed using JVM. The JVM
can use either a plug-in of the Web browser or a separate runtime environment to
run an applet application.
 JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.

An applet is a Java program designed to be included in an HTML Web document. You can
write your Java applet and include it in an HTML page. When you use a Java-enabled
browser to view an HTML page that contains an applet, the applet's code is transferred to
your system and is run by the browser's Java virtual machine.

The HTML document contains tags, which specify the name of the Java applet and its
Uniform Resource Locator (URL). The URL is the location at which the applet bytecodes
reside on the Internet. When an HTML document containing a Java applet tag is displayed, a
Java-enabled Web browser downloads the Java bytecodes from the Internet and uses the
Java virtual machine to process the code from within the Web document. These Java
applets are what enable Web pages to contain animated graphics or interactive content.

Applications of Java Applet

221
The Applets are used to provide interactive features to web applications that cannot be
provided by HTML alone. They can capture mouse input and also have controls like buttons
or check boxes. In response to user actions, an applet can change the provided graphic
content.

Difference between Applet and Application

Java Application Java Applet

Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML web
independently without using the web document. They require a Java-enabled web
browser. browser for execution.

Application program requires a main Applet does not require a main function for its
function for its execution. execution.

Java application programs have the


full access to the local file system and Applets don’t have local disk and network
network. access.

Applets can only access the browser specific


Applications can access all kinds of services. They don’t have access to the local
resources available on the system. system.

Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.

An application program is needed to


perform some task directly for the
user. An applet program is needed to p

Passing Parameters to Applets

In this article we will learn about passing parameters to applets using the param tag and
retrieving the values of parameters using getParameter method.

222
Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.

Param Tag

The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the
value of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:

<param name=”name” value=”Ramesh” />


<param name=”age” value=”25″ />

Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.

getParameter() Method

The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:

String getParameter(String param-name)

Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:

1 import java.awt.*;

2 import java.applet.*;

3 public class MyApplet extends Applet

4 {

5 String n;

223
6 String a;

7 public void init()

8 {

9 n = getParameter("name");

10 a = getParameter("age");

11 }

12 public void paint(Graphics g)

13 {

14 g.drawString("Name is: " + n, 20, 20);

15 g.drawString("Age is: " + a, 20, 40);

16 }

17 }

18 /*

19 <applet code="MyApplet" height="300" width="500">

20 <param name="name" value="Ramesh" />

21 <param name="age" value="25" />

22 </applet>

23 */

Output of the above program is as follows:

224
Creating a Swing Apple

Swing Applets

So far, we have created the applets based on AWT(Abstract Window Toolkit) by extending
the Applet class of the awt package. We can even create applets based on
the Swing package. In order to create such applets, we must extend JApplet class of
the swing package. JApplet extends Applet class, hence all the features of Applet class are
available in JApplet as well, including JApplet's own Swing based features. Swing applets
provides an easier to use user interface than AWT applets.

Some important points :

 When we creat an AWT applet, we implement the paint(Graphics g) method to draw in


it but when we create a Swing applet, we implement paintComponent(Graphics
g) method to draw in it.
 For an applet class that extends Swing's JApplet class, the way elements like textfield,
buttons, checksboxes etc are added to this applet is performed by using a default layout
manager, i.e. BorderLayout

Note:

JApplet is a top-level container class and you should never draw on it directly, instead you
should draw on the component class like JPanel and then add this JPanel to the JApplet, as
shown in the upcoming code.

225
 Creating a swing applet

 In the upcoming code, first, we have created a swing applet by extending JApplet class
and we have added a JPanel to it.
 Next, we have created a class B, which has extended JPanel class of Swing package and
have also implemented ActionListener interace to listen to the button click event
generated when buttons added to JPanel are clicked.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="Applet21" width="500" height="200">
</applet>
*/

public class Applet21 extends JApplet


{

public void init()


{
add(new B()); //Adding a JPanel to this Swing applet
}

class B extends JPanel implements ActionListener


{
JLabel jb;
JButton Box2, box2, box3, box4;
String str;

B()

226
{
jb= new JLabel("Welcome, please click on any button to unbox some interesting
knowledge -");
Box2 = new JButton("Box2");
box2 = new JButton("Box2");
box3 = new JButton("Box3");
box4 = new JButton("Box4");

str ="";

setLayout(new FlowLayout());

add(jb);
add(Box2);
add(box2);
add(box3);
add(box4);

Box2.addActionListener(this);
box2.addActionListener(this);
box3.addActionListener(this);
box4.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand().equals("Box2"))
{
str="Amazon is the largest tropical rain forest, covering 40% of the South America
Continent.";
repaint();
}

if(ae.getActionCommand().equals("Box2"))
{
str="The Mariana Trench is the deepest point in Earth's ocean, with depth of over
10,994 metres.";
repaint();
}

if(ae.getActionCommand().equals("Box3"))
{
str="The coldest temperature ever recorded was -128.6F in Antarctica, on July 21,
1983.";
repaint();
}

227
if(ae.getActionCommand().equals("Box4"))
{
str="The oldest person to climb Mt. Everent was Japanese Miura Yiuchiro, at the age
of 80.";
repaint();
}

public void paintComponent(Graphics g)


{
super.paintComponent(g);
g.drawString(str, 2, 170);
}

Output-

In the applet shown above, four buttons are presented in the output. These buttons are
added to B class(which has extended JPanel). This JPanel is in turn added to our Swing
applet class, Applet21. Whenever a button is clicked, an interesting fact about the
world is presented to the user.

Painting in Applet

We can perform painting operation in applet by the mouseDragged() method of

228
MouseMotionListener.

Example of Painting in Applet:

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>

Exploring Swing Controls

In this article, I am going to discuss Swing Controls in Java with Examples. Please read our
previous article, where we discussed Swings in Java. At the end of this article, you will
understand the following swing controls in Java in detail with examples.
1. JLabel
2. JRadioButton
3. ButtonGroup

229
4. JCheckBox
5. JTextField
6. JTextArea
7. JButton
8. Border
9. JComboBox
10. JTabbedPane
11. JPasswordField
12. Look and Feel Management in Java Swing
JLabel
The object of the JLabel class may be a component for putting text during a container. It’s
used to display one line of read-only text. The text is often changed by an application but a
user cannot edit it directly. It inherits the JComponent class.
Declaration: public class JLabel extends JComponent implements SwingConstants,
Accessible
Syntax: JLabel jl = new JLabel();
JLabel Constructors
1. JLabel(): It is used to create a JLabel instance with no image and with an empty
string for the title.
2. JLabel(String s): It is used to create a JLabel instance with the specified text.
3. JLabel(Icon i): It is used to create a JLabel instance with the specified image.
4. JLabel(String s, Icon I, int horizontalAlignment): It is used to create a JLabel
instance with the specified text, image, and horizontal alignment.
Sample Program to understand JLabel Swing Control in Java:
import javax.swing.*;

import java.awt.*;

public class JLabelDemo extends JFrame

JLabel jl;
JLabelDemo ()
{
jl = new JLabel ("Good Morning");
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
c.setBackground (Color.blue);
Font f = new Font ("arial", Font.BOLD, 34);
jl.setFont (f);
jl.setBackground (Color.white);
c.add (jl);
this.setVisible (true);
this.setSize (400, 400);
this.setTitle ("Label");
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

230
}
public static void main (String[]args)
{
new JLabelDemo ();
}
}
Output

JRadioButton
This component allows the user to select only one item from a group item. By using the
JRadioButton component you can choose one option from multiple options.
Declaration: public class JRadioButton extends JToggleButton implements Accessible
Syntax: JRadioButton jrb = new JRadioButton();
JRadioButton Constructors
1. JRadioButton(): It is used to create an unselected radio button with no text.
2. JRadioButton(Label): It is used to create an unselected radio button with specified
text.
3. JRadioButton(Label, boolean): It is used to create a radio button with the
specified text and selected status.
ButtonGroup
This class is used to place multiple RadioButton into a single group. So the user can select
only one value from that group. We can add RadioButtons to the ButtonGroup by using the
add method.
Example : add(jrb);
Syntax : ButtonGroup bg = new ButtonGroup();
JCheckBox
This component allows the user to select multiple items from a group of items. It is used to
create a CheckBox. It is used to turn an option ON or OFF.
Declaration: public class JCheckBox extends JToggleButton implements Accessible
JCheckBox Constructors
1. JCheckBox(): It is used to create an initially unselected checkbox button with no
text, no icon.
2. JCheckBox(Label): It is used to create an initially unselected checkbox with text.
3. JCheckBox(Label, boolean): It is used to create a checkbox with text and specifies
whether or not it is initially selected.

231
4. JCheckBox(Action a): It is used to create a checkbox where properties are taken
from the Action supplied.
JTextField
The JTextField component allows the user to type some text in a single line. It basically
inherits the JTextComponent class.
Declaration: public class JTextField extends JTextComponent implements
SwingConstants
Syntax: JTextField jtf = new JTextField();
JTextField Constructors
1. JTextField(): It is used to create a new Text Field.
2. JTextField(String text): It is used to create a new Text Field initialized with the
specified text.
3. JTextField(String text, int columns): It is used to create a new Text field initialized
with the specified text and columns.
4. JTextField(int columns): It is used to create a new empty TextField with the
specified number of columns.
JTextArea
The JTextArea component allows the user to type the text in multiple lines. It also allows
the editing of multiple-line text. It basically inherits the JTextComponent class.
Declaration: public class JTextArea extends JTextComponent
Syntax: JTextArea jta = new JTextArea();
JTextArea Constructors
1. JTextArea(): It is used to create a text area that displays no text initially.
2. JTextarea(String s): It is used to create a text area that displays specified text
initially.
3. JTextArea(int row, int column): It is used to create a text area with the specified
number of rows and columns that display no text initially.
4. JTextarea(String s, int row, int column): It is used to create a text area with the
specified number of rows and columns that display specified text.
Sample Program to understand the above-discussed Swing Controls in Java.
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class SwingDemo2 extends JFrame implements ActionListener
{
JRadioButton eng, doc;
ButtonGroup bg;
JTextField jtf;
JCheckBox bcd, ccb, acb;
JTextArea jta;
SwingDemo2 ()
{
eng = new JRadioButton ("Engineer");
doc = new JRadioButton ("Doctor");
bg = new ButtonGroup ();

232
bg.add (eng);
bg.add (doc);
jtf = new JTextField (20);
bcd = new JCheckBox ("Bike");
ccb = new JCheckBox ("Car");
acb = new JCheckBox ("Aeroplane");
jta = new JTextArea (3, 20);
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
// Registering the listeners with the components
eng.addActionListener (this);
doc.addActionListener (this);
bcd.addActionListener (this);
ccb.addActionListener (this);
acb.addActionListener (this);
c.add (eng);
c.add (doc);
c.add (jtf);
c.add (bcd);
c.add (ccb);
c.add (acb);
c.add (jta);
this.setVisible (true);
this.setSize (500, 500);
this.setTitle ("Selection Example");
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == eng)
{
jtf.setText ("You are an Engineer");
}
if (ae.getSource () == doc)
{
jtf.setText ("You are an Doctor");
}
String str = " ";
if (bcd.isSelected ())
{
str += "Bike\n";
}
if (ccb.isSelected ())
{
str += "Car\n";
}

233
if (acb.isSelected ())
{
str += "Aeroplane\n";
}
jta.setText (str);
}
public static void main (String[]args)
{
new SwingDemo2 ();
}
}
Output:

JButton
This component can be used to perform some operations when the user clicks on it. When
the button is pushed, the application results in some action. It basically inherits the
AbstractButton class.
Declaration: public class JButton extends AbstractButton implements Accessible
Syntax: JButton jb = new JButton();
JButton Constructors
1. JButton(): It is used to create a button with no text and icon.
2. JButton(String s): It is used to create a button with the specified text.
3. JButton(Icon i): It is used to create a button with the specified icon object.
Border
The border is an interface using which we can apply a border to every component. To
create the borders we have to use the methods available in BorderFactory class. We can
apply the created border to any component by using SetBorder() method.
Component.setBorder(Border);
Methods of Border
1. Border createLineBorder(Color, int): It is used to create a line border. Here, Color
object specifies the color of the line and int specifies the width in pixels of the line.
2. Border createEtchedBorder(int, Color, Color): It is used to create an etched
border. Here, Color arguments specify the highlight and shadow colors to be used.
Here, int arguments allow the border methods to be specified as
either EtchedBorder.RAISED or EtchedBorder.LOWERED. The methods without
the int arguments create a lowered etched border.

234
3. Border createBevelBorder(int, Color, Color): It is used to create a raised or
lowered beveled border, specifying the colors to use. Here, the integer argument can
be either BevelBorder.RAISED or BevelBorder.LOWERED. Here, Color specifies the
highlight and shadow colors.
4. MatteBorder createMatteBorder(int, int, int, int, Icon): It is used to create a
matte border. Here, the integer arguments specify the number of pixels that the
border occupies at the top, left, bottom, and right (in that order) of whatever
component uses it. Here, the color argument specifies the color which with the
border should fill its area. Here, the icon argument specifies the icon which with the
border should tile its area.
5. TitledBorder createTitledBorder(Border, String, int, int, Font, Color): Create a
titled border. Here, the string argument specifies the title to be displayed. Here, the
optional font and color arguments specify the font and color to be used for the title’s
text. Here, the border argument specifies the border that should be displayed along
with the title. Here, the integer arguments specify the number of pixels that the
border occupies at the top, left, bottom, and right (in that order) of whatever
component uses it.
6. CompoundBorder createCompoundBorder(Border, Border): Combine two
borders into one. Here, the first argument specifies the outer border; the second, the
inner border.
Sample Program to understand JButton and Border controls in Swing Java:
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame
{
private JButton button[];
private JPanel panel;
public JButtonDemo ()
{
setTitle ("JButton Borders");
panel = new JPanel ();
panel.setLayout (new GridLayout (7, 1));
button = new JButton[7];
for (int count = 0; count < button.length; count++)
{
button[count] = new JButton ("Button " + (count + 1));
panel.add (button[count]);
}
button[0].setBorder (BorderFactory.createLineBorder (Color.blue));
button[1].setBorder (BorderFactory.createBevelBorder (0));
button[2].setBorder (BorderFactory.createBevelBorder (1, Color.red, Color.blue));
button[3].setBorder (BorderFactory.createBevelBorder (1, Color.green,
Color.orange,Color.red, Color.blue));
button[4].setBorder (BorderFactory.createEmptyBorder (10, 10, 10, 10));
button[5].setBorder (BorderFactory.createEtchedBorder (0));
button[6].setBorder (BorderFactory.createTitledBorder ("Titled Border"));

235
add (panel, BorderLayout.CENTER);
setSize (400, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[]args)
{
new JButtonDemo ();
}
}
Output:

JComboBox
This component will display a group of items as a drop-down menu from which one item
can be selected. At the top of the menu the choice selected by the user is shown. It basically
inherits JComponent class. We can add the items to the ComboBox by using the addItem()
method.
Example: jcb.addItem(item);
Declaration: public class JComboBox extends JComponent implements
ItemSelectable, ListDataListener, ActionListener, Accessible
Syntax: JComboBox jcb = new JComboBox();
JComboBox Constructors
1. JComboBox(): It is used to create a JComboBox with a default data model.
2. JComboBox(Object[] items): It is used to create a JComboBox that contains the
elements in the specified array.
3. JComboBox(Vector<?> items): It is used to create a JComboBox that contains the
elements in the specified Vector.
Sample Program to understand JComboBox control in Java
import javax.swing.*;
public class JComboBoxDemo
{
JFrame f;
JComboBoxDemo ()
{

236
f = new JFrame ("ComboBox Example");
String country[] ={ "Hyderabad", "Chennai", "Bengaluru", "Mumbai", "Delhi" };
JComboBox cb = new JComboBox (country);
cb.setBounds (50, 50, 90, 20);
f.add (cb);
f.setLayout (null);
f.setSize (400, 500);
f.setVisible (true);
}
public static void main (String[]args)
{
new JComboBoxDemo ();
}
}
Output:

JTabbedPane
It is a pane that can contain tabs and each tab can display any component in the same pane.
It is used to switch between a group of components by clicking on a tab with a given title or
icon. To add the tabs to the JTabbedPane we can use the following methods:
jtp.add(TabName, Components)
jtp.addTab(TabName, Components)
Declaration: public class JTabbedPane extends JComponent implements Serializable,
Accessible, SwingConstants
Syntax: JTabbedPane jtp = new JTabbedPane();
JTabbedPane Constructors
1. JTabbedPane(): It is used to create an empty TabbedPane.
2. JTabbedPane(int tabPlacement): It is used to create an empty TabbedPane with a
specified tab placement.
3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): It is used to create an
empty TabbedPane with a specified tab placement and tab layout policy.
Sample Program to understand JTabbedPane control in Java
import javax.swing.*;
import java.awt.*;
public class JTabbedPaneDemo

237
{
public static void main (String args[])
{
JFrame frame = new JFrame ("Technologies");
JTabbedPane tabbedPane = new JTabbedPane ();
JPanel panel1, panel2, panel3, panel4, panel5;
panel1 = new JPanel ();
panel2 = new JPanel ();
panel3 = new JPanel ();
panel4 = new JPanel ();
panel5 = new JPanel ();
tabbedPane.addTab ("Cricket", panel1);
tabbedPane.addTab ("Badminton ", panel2);
tabbedPane.addTab ("Football", panel3);
tabbedPane.addTab ("Basketball ", panel4);
tabbedPane.addTab ("Tennis", panel5);
frame.add (tabbedPane);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (550, 350);
frame.setVisible (true);
}
}
Output:

JPasswordField
It is a text component specialized for password entry. It allows the editing of a single line of
text. It basically inherits the JTextField class.
Declaration: public class JPasswordField extends JTextField
Syntax: JPasswordField jpf = new JPasswordField();
JPasswordFiled Constructors
1. JPasswordField(): It is used to construct a new JPasswordField, with a default
document, null starting text string, and column width.
2. JPasswordField(int columns): It is used to construct a new empty JPasswordField
with the specified number of columns.

238
3. JPasswordField(String text): It is used to construct a new JPasswordField
initialized with the specified text.
4. JPasswordField(String text, int columns): It is used to construct a new
JPasswordField initialized with the specified text and columns.
Sample Program to understand JPasswordFiled Swing control in Java
import javax.swing.*;
public class JPasswordFieldDemo
{
public static void main (String[]args)
{
JFrame f = new JFrame ("Password Field Example");
JPasswordField value = new JPasswordField ();
JLabel l1 = new JLabel ("Password:");
l1.setBounds (20, 100, 80, 30);
value.setBounds (100, 100, 100, 30);
f.add (value);
f.add (l1);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
}
Output:

Look and Feel Management in Java Swing


To manage a look and feel for the UI components swing package provides look and feel
managers. In the Swing environment, look and feel are controlled by the UI Manager class.
Look and Feel Managements are shown below:
1. MetalLookAndFeel
2. MotifLookAndFeel
3. NimbusLooAndFeel (added from Java1.6)

239
4. WindowsLookAndFeel
5. WindowsClassicLookAndFeel
The above looks and feels are the predefined classes.
Steps to apply a look and feel:
1. Decide a look and feel type and inform a UI Manager to set a given look and feel and
this will be done using setLookAndFeel().
2. Once the look and feel are set we can apply to the UI Component or Component tree
(whole window).
Note: To update a UI component, we need to call updateUI() to update the look and feel
settings to the component. To update a whole component tree we need to call
updateComponentTreeUI() from SwingUtilities class.
Sample Program for Look and Feel Management in Java Swing
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class LookAndFeelDemo
{
static JFrame jf;
public static void main (String[]args)
{
jf = new JFrame ();
jf.setSize (250, 250);
FlowLayout ob = new FlowLayout ();
jf.setLayout (ob);
JButton jb1 = new JButton ("Metal");
JButton jb2 = new JButton ("Nimbus");
JButton jb3 = new JButton ("Motif");
JButton jb4 = new JButton ("Windows");
MyListener ob1 = new MyListener ();
jb1.addActionListener (ob1);
jb2.addActionListener (ob1);
jb3.addActionListener (ob1);
jb4.addActionListener (ob1);
jf.add (jb1);
jf.add (jb2);
jf.add (jb3);
jf.add (jb4);
jf.setVisible (true);
}
}
class MyListener implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
try

240
{
String buttonname = ae.getActionCommand ();
if (buttonname.equals ("Metal"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.MetalLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Nimbus"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Motif"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Windows"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
}
catch (Exception e1)
{
}
}
}
Output:

In the next article, I am going to discuss the Swing Dialog box in Java with examples. Here,
in this article, I try to explain Swing Controls in Java with Examples and I hope you enjoy
this Swing Controls in Java with Examples article.

241
Swing Dialog Boxes in Java with Examples
In this article, I am going to discuss Swing Dialog boxes in Java with Examples. Please
read our previous article, where we discussed Swing Controls in Java. At the end of this
article, you will understand the different Dialog Boxes that are available in Java Swings
with Examples.
Dialog box : JOptionPane
Dialog Box is a small pop-up box and that was used for different cases like confirmation,
warning, message, etc. Dialog boxes are of three types:
1. Confirmation
2. Input
3. Message
Swing package provides a special class i.e. JOptionPane which was used for creating above
dialog boxes as ready-made.
Declaration: public class JOptionPane extends JComponent implements Accessible
JOptionPane Constructors
1. JOptionPane(): Creates a JOptionPane with a test message.
2. JOptionPane(Object message): Creates an instance of JOtionPane to display a
message.
3. JOptionPane(Object message, int messageType): Creates an instance of
JOtiopnPane to display a message with specified message type and default options.
JOptionPane Methods
Some of the static methods in the JOptionPane class are as follows:
1. showConfirmDialog(Component parentComponent, Object message): Creates a
dialog box with the option Yes, No, and Cancel; with the title, Select an Option.
2. showInputDialog(Component parentComponent, Object message): It show a
question-message dialog box requesting input from the user parented to parent
component.
3. showMessageDialog(Component parentComponent, Object message): Creates
an information-message dialog box titled “Message”.
Sample Program Message Dialog Box in Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JOptionPaneDemo
{
static JTextField jf1;
public static void main (String[]args)
{
JFrame jf = new JFrame ();
jf.setSize (250, 250);
FlowLayout ob = new FlowLayout ();
jf.setLayout (ob);
JLabel j1 = new JLabel ("Enter Name");
jf1 = new JTextField (10);
JButton jb = new JButton ("Submit");
MyListener1 ob1 = new MyListener1 ();

242
jb.addActionListener (ob1);
jf.add (j1);
jf.add (jf1);
jf.add (jb);
jf.setVisible (true);
}
}
class MyListener1 implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
String name = JOptionPaneDemo.jf1.getText ();
JOptionPane.showMessageDialog (null, "Welcome," + name);
}
}
Output:

The appeared Dialog Box looks like:

243

You might also like