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

Java Programming Lecture Notes

Uploaded by

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

Java Programming Lecture Notes

Uploaded by

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

LECTURE NOTES ON

JAVA PROGARMMING (20A05505a)


III B.TECH I SEMESTER
(JNTUA-R20)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


MOTHER THERESA INSTITUTE OF ENGINEERING & TECHNOLOGY
Melumoi,PALAMANER-517408
(Approved by AICTE, New Delhi Affiliated to JNTUA Ananthapuramu. ISO 9001:2015 Certified
Institute)
JAVA UNIT-I

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his team changed
the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as


a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Introduction to Object Oriented Programming:

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

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

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
When one object acquires all the properties and behaviors of a parent object, it is known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

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.
The History and Evolution of JAVA:

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.
Following are given significant points that describe the history of Java.

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 it was 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 was named as "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.

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 chose the name Java 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 in 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 a cup of coffee nearby 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 was released on 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 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.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

Introduction to Classes, Objects

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.


Creating a Class:

To create class use the keyword: CLASS

Public class Main {

Int x=5;

Create an Object:

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

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

Public class Main {

Int x=5;

Public static void main (string[] args) {

Main myobj=new Main();

System.out.println(myobj.x);

Create two objects of Main:

publicclassMain{

int x =5;

publicstaticvoidmain(String[]args){

MainmyObj1=newMain();// Object 1

MainmyObj2=newMain();// Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

}
Methods:

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known
as functions.To reuse code: define the code once, and use it many times.

Create a method inside Main:

publicclassMain{

staticvoidmyMethod(){

// code to be executed

Inside main, call the myMethod() method:

publicclassMain{

staticvoidmyMethod(){

System.out.println("I just got executed!");

publicstaticvoidmain(String[]args){

myMethod();

// Outputs "I just got executed!"

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

publicclassMain{
staticvoidmyMethod(Stringfname){

System.out.println(fname+" Refsnes");

publicstaticvoidmain(String[]args){

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// AnjaRefsnes

Constructors:
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes.

Create a constructor:

// Create a Main class

publicclassMain{

int x;// Create a class attribute

// Create a class constructor for the Main class

publicMain(){

x =5;// Set the initial value for the class attribute x

publicstaticvoidmain(String[]args){

MainmyObj=newMain();// Create an object of class Main (This will call the


constructor)

System.out.println(myObj.x);// Print the value of x


}

// Outputs 5

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

publicclassMain{

int x;

publicMain(int y){

x = y;

publicstaticvoidmain(String[]args){

MainmyObj=newMain(5);

System.out.println(myObj.x);

// Outputs 5

Java this Keyword:

The this keyword refers to the current object in a method or constructor.

The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name (because a class
attribute is shadowed by a method or constructor parameter). If you omit the
keyword in the example above, the output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

publicclassMain{

int x;

// Constructor with a parameter

publicMain(int x){

this.x= x;

// Call the constructor

publicstaticvoidmain(String[]args){

MainmyObj=newMain(5);

System.out.println("Value of x = "+myObj.x);

Garbage Collection:garbage means unreferenced objects


Garbage Collection is process of reclaiming the runtime unused memory automatically.
In other words, it is a way to destroy the unused objects. we were using free() function in
C language and delete() in C++. But, in java it is performed automatically. So, java
provides better memory management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.

There are many ways:

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc.

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

2) By assigning a reference to another:

1. Employee e1=new Employee();


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

3) By anonymous object:

1. new Employee();

public class TestGarbage1{


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

object is garbage collected


object is garbage collected
object is garbage collected

Java Data Types :a variable in Java must be a specified data type


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

A primitive data type specifies the size and type of variable values, and it has
no additional methods.

Byte, Short, Int, Long, Float, Boolean, Char, Double these are the eight
primitive date types in java.
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).

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
bytemyNum=100;

System.out.println(myNum);

Short
The short data type can store whole numbers from -32768 to 32767:

Example
shortmyNum=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
intmyNum=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
longmyNum=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.

The float and double data types can store fractional numbers. Note that you should end the value
with an "f" for floats and "d" for doubles:

Float Example
floatmyNum=5.75f;

System.out.println(myNum);

Double Example
doublemyNum=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);

Boolean Types
A boolean data type is declared with the boolean keyword and can only take the
values true or false:

Example
booleanisJavaFun=true;

booleanisFishTasty=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
charmyGrade='B';

System.out.println(myGrade);
Example
char myVar1 =65, myVar2 =66, myVar3 =67;

System.out.println(myVar1);

System.out.println(myVar2);

System.out.println(myVar3);

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

Java Variables
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -
123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax
typevariableName= value;
Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to
assign values to the variable.

To create a variable that should store text, look at the following example:

Example
Create a variable called name of type String and assign it the value "John":

String name ="John";

System.out.println(name);

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

intmyNum=15;

System.out.println(myNum);

You can also declare a variable without assigning the value, and assign the
value later:

Example
intmyNum;

myNum=15;

System.out.println(myNum);

Declare Many Variables


To declare more than one variable of the same type, you can use a comma-
separated list:

Example
Instead of writing:

int x =5;

int y =6;

int z =50;

System.out.println(x + y + z);
You can simply write:

int x =5, y =6, z =50;

System.out.println(x + y + z);

One Value to Multiple Variables


You can also assign the same value to multiple variables in one line:

Example
int x, y, z;

x = y = z =50;

System.out.println(x + y + z);

Java Type Casting


Type casting is when you assign a value of one primitive data type to another
type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger


type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller


size type
double -> float -> long -> int -> char -> short -> byte

 Widening Casting
 Widening casting is done automatically when passing a smaller size type
to a larger size type:
 Example
 publicclassMain{
 publicstaticvoidmain(String[]args){
 intmyInt=9;
 doublemyDouble=myInt;// Automatic casting: int to double

 System.out.println(myInt);// Outputs 9
 System.out.println(myDouble);// Outputs 9.0
 }
 }


 Narrowing Casting
 Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
 Example
 publicclassMain{
 publicstaticvoidmain(String[]args){
 doublemyDouble=9.78d;
 intmyInt=(int)myDouble;// Manual casting: double to int

 System.out.println(myDouble);// Outputs 9.78
 System.out.println(myInt);// Outputs 9
 }
 }

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++,
we need to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.

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

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


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

Declaration, Instantiation and Initialization of Java Array


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

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

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

1. //Java Program to illustrate the use of declaration, instantiation


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

For-each Loop for Java Array


We can also print the Java array using for-each loop

. The Java for-each loop prints the array elements one by one. It holds an array element in a variable,
then executes the body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }

Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

Output: 33 3 4 5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array


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

Output: 3
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, /
etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift Shift <<>>>>>

Relational comparison <><= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||
Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --

1. public class OperatorExample{


2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:
22
21

Java Unary Operator Example: ~ and !

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}

Output:

-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression

1. public class OperatorExample{


2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}

Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of
a specified number of times.

Java Left Shift Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Output:

40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by
the number of bits specified by the right operand.

Java Right Shift Operator Example

1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

Output:

2
5
2

Java Shift Operator Example: >>vs>>>

1. public class OperatorExample{


2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check the second condition if the first condition is false.
It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or
false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

Output:

false
false

Java AND Operator Example: Logical &&vs Bitwise &

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or
false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}

Output:

true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.

Java Ternary Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.

Java Assignment Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:

14
16

Java Assignment Operator Example

1. public class OperatorExample{


2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:

Compile time error

After type cast:

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Output:

20

Java Control Statements


Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides statements
that can be used to control the flow of Java code. Such statements are called control flow
statements. It is one of the fundamental features of Java, which provides a smooth flow of
program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types
of decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives
a Boolean value, either true or false. In Java, there are four types of if-statements given
below.

1. if-else statement
2. if-else-if ladder
3. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Consider the following example in which we have used the if statement in the java code.
Student.java

Student.java

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }

Output:

x + y is greater than 20

2) if-else statement

The if-else statement

is an extension to the if-statement, which uses another block of code, i.e., else block. The else
block is executed if the condition of the if-block is evaluated as false.

Syntax:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

Consider the following example.

Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }

Output:

x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if-else statements that
create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Consider the following example.


Student.java

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }

Output:

Delhi

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.

Syntax of Nested if-statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

Consider the following example.

Student.java

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }

Output:

Delhi

Switch Statement:
In Java, Switch statements

are similar to if-else-if statements. The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the
program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }

Consider the following example to understand the flow of the switch statement.

Student.java

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }

Output:

While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch permits
only int, string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the set
of instructions in a repeated order. The execution of the set of instructions depends
upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, for loop

is similar to C
and C++
. It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }

The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in
java.

Calculation.java

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax to
use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Consider the following example to understand the functioning of the for-each loop in
Java.

Calculation.java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop
is also used to iterate over the number of statements multiple times. However, if we don't know
the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start
of the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.

The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }

The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop

checks the condition at the end of the loop after executing the loop statements. When the number
of iteration is not known and we have to execute the loop at least once, we can use do-while
loop.

It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in
Java.

Calculation.java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the other
part of the program. There are two types of jump statements in Java, i.e., break and
continue.

Java break statement


As the name suggests, the break statement

is used to break the current flow of the program and transfer the control to the next statement
outside a loop or switch statement. However, it breaks only the inner loop in the case of the
nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for
loop.

BreakExample.java

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:
0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

1. public class Calculation {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }

Output:

0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement

doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

1. public class ContinueExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }

Output:

0
1
2
3
5
1
2
3
5
2
3
5
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

Example
intmyMethod(int x)

floatmyMethod(float x)

doublemyMethod(double x,double y)

Consider the following example, which has two methods that add numbers of
different type:

Example
staticintplusMethodInt(int x,int y){

return x + y;

staticdoubleplusMethodDouble(double x,double y){

return x + y;

publicstaticvoidmain(String[]args){

int myNum1 =plusMethodInt(8,5);

double myNum2 =plusMethodDouble(4.3,6.26);

System.out.println("int: "+ myNum1);

System.out.println("double: "+ myNum2);

Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the plusMethod method to work for
both int and double:

Example
staticintplusMethod(int x,int y){

return x + y;

staticdoubleplusMethod(double x,double y){

return x + y;

publicstaticvoidmain(String[]args){

int myNum1 =plusMethod(8,5);

double myNum2 =plusMethod(4.3,6.26);

System.out.println("int: "+ myNum1);

System.out.println("double: "+ myNum2);

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be
defined as the concept of having more than one constructor with different parameters
so that every constructor can perform a different task.

Consider the following Java

program, in which we have used different constructors in the class.

Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }

Java Pass by Value


People usually take the pass by value and pass by reference terms together. It is really
confusing and overhear questions in interviews, Is java pass by value or passes by
reference, or both? So the answer to this question is Java is strictly pass by value. There
is no pass by reference in Java.

Let's understand what some of the different mechanisms for passing parameters to
functions are:

o value
o reference
o result
o value-result
o name

Nowadays, the two most used and common mechanisms are pass by value and pass by
reference. Let's discuss them:

Pass by Value: In the pass by value concept, the method is called by passing a value.
So, it is called pass by value. It does not affect the original parameter.
Pass by Reference: In the pass by reference concept, the method is called using an alias
or reference of the actual parameter. So, it is called pass by reference. It forwards the
unique identifier of the object to the method. If we made changes to the parameter's
instance member, it would affect the original value.

Javadoes not support pass by reference concept.

About the Parameters Passed in Java


The fundamental concept for passing the parameters in modern programming
languages is passing by value and passing by reference. But, in Java, the pass by
reference concept is degraded. It supports only the pass by value concept.

The primitive variables hold the actual values, whereas the non-primitive variables hold
the reference variable. However, both variables use stack memory to store the values.
See more about data types in Java

In Java, during the method invokation, a copy of each argument is created then passed
to the method.

In the case of primitive data types, it copies the value inside stack memory then pass it
to the method. In the case of non-primitive data types, it points a reference in stack
memory to actual data, which occurs in a heap. When we pass an object, it will copy a
reference from the stack memory and pass it to the callee method.

Let's demonstrate it with some examples:

Create a Bike class having objects and methods.

Bike.java

1. public class Bike {


2. private double speed;
3. public void Model(){}
4. public Bike(double s){
5. this.speed=s;6.
}
7. public double getSpeed() {
8. return speed;9.
}
10. public void setSpeed(double s1) {
11. this.speed = speed;
12. }
13. }

Now, create a TestSpeed class to swap variables:

TestSpeed.java

1. public class TestSpeed {


2. public static void main(String[] args) {
3. Bike apache = new Bike(180); //memory references
4. Bike pulsar = new Bike(200);
5.
6. swap(apache, pulsar);
7. System.out.println("Apache's Speed is ="+apache.getSpeed());
8. System.out.println("Pulsar's Speed is ="+pulsar.getSpeed());
9. Demo(pulsar);
10. System.out.println("Pulsar's Speed is ="+pulsar.getSpeed());
11. }
12.
13. private static void Demo(Bike b) {
14. b.setSpeed(180);
15. b = new Bike(280);
16. b.setSpeed(200);
17. }
18. public static void swap(Object o1, Object o2)// method for swapping variables
19. {
20. Object temp = o1;
21. o1=o2;
22. o2=temp;
23. }
24. }

Output:

Apache's Speed is =180.0


Pulsar's Speed is =200.0
Pulsar's Speed is =200.0
From the above output, we can see that the swap method did not work. It did not work
because Java is pass by value, and, here, we are passing the reference of the object. So it
is clear that Java does not support pass by reference.

Explanation: In the above program, when we create an instance of the class Bike using
the new operator, the instance of the class is created, and the variable holds the
reference of the memory where the object is saved.

While calling the swap() method, we have created two new variables o1 and o2, which
are pointing to the memory location of the apache and pulsar variable. Below is the
swap method implementation in the above program:

1. public static void swap(Object o1, Object o2)


2. {
3. Object temp = o1;
4. o1=o2;
5. o2=temp;
6. }

As we can see from the above code snippet, the values of o1 and o2 are changed. They
are copies of the apache and pulsar reference locations. So, it did not change the values
of apache and pulsar in the output.

Java Pass by Value Example


Passing the parameters by values does not affect the original variable. Below is the
example of Passing by Value:

PBVDemo.java

1. public class PBVDemo {


2. int a=100;
3. void change(int a){
4. a=a+100;//Changing values It will be locally)
5. }
6. public static void main(String args[]){
7. PBVDemo p=new PBVDemo(); //Creating object
8. System.out.println(" Value (before change)="+p.a);
9. p.change(500); //Passing value
10. System.out.println(" Value (after change)="+p.a);
11. }
12. }

Output:

Value (before change)= 100


Value (after change)= 100

As we can see from the above output, the original values is not affected by the pass by
value mechanism.

Call by Value and Call by Reference in Java


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

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
Output:before change 50
after change 50

Another Example of call by value in java


In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:

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

Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:

Example
Use recursion to add all of the numbers up to 10.

publicclassMain{

publicstaticvoidmain(String[]args){

int result =sum(10);

System.out.println(result);

publicstaticintsum(int k){

if(k >0){

return k +sum(k -1);

}else{

return0;

Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the function
just returns 0. When running, the program follows these steps

Since the function does not call itself when k is 0, the program stops there and
returns the result.

Java Strings
Strings are used for storing text.

A String variable contains a collection of characters surrounded by double


quotes:

Example
Create a variable of type String and assign it a value:

String greeting ="Hello";


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
String txt ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println("The length of the txt string is: "+txt.length());

More String Methods


There are many string methods available, for
example toUpperCase() and toLowerCase():

Example
String txt ="Hello World";

System.out.println(txt.toUpperCase());// Outputs "HELLO WORLD"

System.out.println(txt.toLowerCase());// Outputs "hello world"

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of
a specified text in a string (including whitespace):

Example
String txt ="Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate"));// Outputs 7

Java counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...

String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
StringfirstName="John";

StringlastName="Doe";

System.out.println(firstName+" "+lastName);

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
StringfirstName="John ";

StringlastName="Doe";

System.out.println(firstName.concat(lastName));

Adding Numbers and Strings


WARNING!

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x =10;

int y =20;

int z = x + y;// z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

Example
String x ="10";

String y ="20";
String z = x + y;// z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:

Example
String x ="10";

int y =20;

String z = x + y;// z will be 1020 (a String)

Special Characters
Because strings must be written within quotes, Java will misunderstand this
string, and generate an error:

String txt ="We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string
characters:

Escape character Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash

The sequence \" inserts a double quote in a string:

Example
String txt ="We are the so-called \"Vikings\" from the north.";
The sequence \' inserts a single quote in a string:

Example
String txt ="It\'s alright.";

The sequence \\ inserts a single backslash in a string:

Example
String txt ="The character \\ is called backslash.";

Other common escape sequences that are valid in Java are:

Code Result

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed
Inheritance
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


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

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.
o 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.
o 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.
o 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.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of
Employee.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

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

When one class inherits multiple classes, it is known as multiple inheritance. For Example:
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.

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.

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.

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

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

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


We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use
super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog
class, it will call the eat() method of Dog class by default because priority is given to local.
To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

As we know well that default constructor is provided by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.

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

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person
will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from
child class. In such way, we are reusing the parent class constructor.

class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Output:

1 ankit 45000

Creating multilevel hierarchy in java

In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel inheritance a
subclass is derived from a derived class. One class inherits only single class. Therefore, in multilevel inheritance, every time
ladder increases by one. The lower most class will have the properties of all the super classes’.

It is common that a class is derived from another derived class.The class student serves as a base class for the derived class
marks, which in turn serves as a base class for the derived class percentage.The class marks is known as intermediates base
class since it provides a link for the inheritance between student and percentage.The chain is known as inheritance path. When
this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage
inherits all aspects of marks and student.

Example for multilevel hierarchy:

class student
{
int rollno;
String name;

student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}

class marks extends student


{
int total;
marks(int r, String n, int t)
{
super(r,n); //call super class (student) constructor
total = t;
}
void dispdatam()
{
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}

class percentage extends marks


{
int per;

percentage(int r, String n, int t, int p)


{
super(r,n,t); //call super class(marks) constructor
per = p;
}
void dispdatap()
{
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe
{
public static void main(String args[])
{
percentage stu = new percentage(102689, "RATHEESH", 350, 70); //call constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
}

Output:
Rollno = 102689
Name = RATHEESH
Total = 350
Percentage = 70

class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
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
Method Overriding in Java
1. Understanding the problem without method overriding

2. Can we override the static method

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


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

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. 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.

//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:

xVehicle is runningroblem 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:

Bike is running safely


Dynamic method dispatch is the mechanism in which a call to an overridden method is
resolved at run time instead of compile time. This is an important concept because of how Java
implements run-time polymorphism.

Java uses the principle of ‘a superclass reference variable can refer to a subclass object’ to
resolve calls to overridden methods at run time. When a superclass reference is used to call an
overridden method, Java determines which version of the method to execute based on the type
of the object being referred to at the time call.

In other words, it is the type of object being referred to that determines which version of an
overridden method will be executed.

Advantages of dynamic method dispatch

1. It allows Java to support overriding of methods, which are important for run-time
polymorphism.
2. It allows a class to define methods that will be shared by all its derived classes, while also
allowing these sub-classes to define their specific implementation of a few or all of those
methods.
3. It allows subclasses to incorporate their own methods and define their implementation.

Here is an example illustrating dynamic method dispatch:


// Implementing Dynamic Method Dispatch
class Apple
{
void display()
{
System.out.println("Inside Apple's display method");
}
}

class Banana extends Apple


{
void display() // overriding display()
{
System.out.println("Inside Banana's display method");
}
}

class Cherry extends Apple


{
void display() // overriding display()
{
System.out.println("Inside Cherry's display method");
}
}

class Fruits_Dispatch
{
public static void main(String args[])
{
Apple a = new Apple(); // object of Apple
Banana b = new Banana(); // object of Banana
Cherry c = new Cherry(); // object of Cherry

Apple ref; // taking a reference of Apple

ref = a; // r refers to a object in Apple


ref.display(); // calling Apple's version of display()

ref = b; // r refers to a object in Banana


ref.display(); // calling Banana's version of display()

ref = c; // r refers to a object in Cherry


ref.display(); // calling Cherry's version of display()
}
}

This program creates one superclass (i.e., class Apple) and two subclasses of it (i.e., Banana
class and Cherry class). Subclasses Banana and Cherry override the display() method declared in
Apple. Inside the main() method in class Fruits_Dispatch, objects of type Apple, Banana, and
Cherry are declared. A reference of type Apple, called ref, is declared.

The program then assigns a reference to each type of object to ref and uses the reference to
invoke display().

The version of display() executed is determined by the type of the object being referred to at the
time of the call.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java

. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery

Abstraction lets you focus on what the object

does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors

and static methods also.

o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract method.
Example of abstract method

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

Example of Abstract class that has an abstract method

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

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
running safely

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword.

1) Java final variable


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

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error

2) Java final method


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

Example of final method


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

Output:Compile Time Error

Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the topmost
class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent
class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.

Packages:

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.

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

How to compile java package

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

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

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

How to run java package program

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

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

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

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

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

Example of package that import the packagename.*


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

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

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

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

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there is no
need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.

Example of package by import fully qualified name


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

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

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

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

Package
A package is a collection of related Java entities (such as classes, interfaces, exceptions, errors and enums). Packages are
used for:
1. Resolving naming conflict of classes by prefixing the class name with a package name. For
example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same class
name Circle, but they belong to two different packages: com.zzz and com.yyy. These two classes can be used in
the same program and distinguished using the fully-qualified class name - package name plus class name. This
mechanism is called Namespace Management.
2. Access Control: Besides public and private, Java has two access control modifiers – protected and default – that
are related to package. A protected entity is accessible by classes in the same package and its subclasses. An entity
without access control modifier (i.e., default) is accessible by classes in the same package only.
3. For distributing a collection of reusable classes, usually in a format known as Java Archive (JAR) file.
Package Naming Convention
A package name is made up of the reverse of the Internet Domain Name (to ensure uniqueness) plus your own
organization's internal project name, separated by dots '.'. Package names are in lowercase. For example, suppose that
your Internet Domain Name is "zzz.com", you can name your package as "com.zzz.project1.subproject2".
The prefix "java" and "javax" are reserved for core Java packages and Java extensions, respectively.
Package Name & the Directory Structure
The package name is closely associated with the directory structure used to store the classes. For example, the
class Circle of package com.zzz.project1.subproject2 is stored as
"$BASE_DIR\com\zzz\project1\subproject2\Circle.class", where $BASE_DIR denotes the base directory of the
package. Clearly, the "dot" in the package name corresponds to a sub-directory of the file system.
The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime must
be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an environment
variable called CLASSPATH. (CLASSPATH is similar to another environment variable PATH, which is used by the command shell
to search for the executable programs.)
In writing GUI programs, we are often confused by two packages: java.awt and java.awt.event. They are two distinct
packages sharing some common directory structures. The classes belonging to the package java.awt are stored in
directory "$BASE_DIR\java\awt\" while the classes of package java.awt.event are stored in directory
"$BASE_DIR\java\awt\event\". java.awt and java.awt.event are two distinct packages with common prefix and
directory structure. There is no such concept of sub-package in Java (i.e., java.awt.event is not a sub-package
of java.awt).
Creating Packages
To make a class as part of a package, you have to include the package statement as the first statement in the source file.
Example 1
We shall write a class called Circle in package com.yyy. It is a good practice to store the source files and the classes in
separate directories, typically called "src" and "classes". This is to facilitate the distribution of classes without the source
files.
Suppose that our base directory ($BASE_DIR) is d:\myProject. Create two sub-directories "src" and "classes".
Write the Circle.java and save under "src\com\yyy", as follows:
// src\com\yyy\Circle.java
package com.yyy;

public class Circle {


private double radius;
public Circle(double radius) { this.radius = radius; }
public double getRadius() { return radius; }
public void setRadius(double radius) { this.radius = radius; }
public String toString() { return "Circle[radius=" + radius + "]"; }
}
To compile the source using JDK, we need to use the -d option to specify the base directory of the compiled class, i.e.,
"classes", as follows::
// Change directory to the package base directory
> d:
> cd myProject

// Compile
> javac -d classes src/com/yyy/Circle.java
// NOTE: you can use either forward slash or backward slash as directory separator in javac

// Show the directories/files


> tree /f /a
Folder PATH listing for volume winSystem
Volume serial number is 6A19-E18C
C:.
+---classes
| \---com
| \---yyy
| Circle.class
|
\---src
\---com
\---yyy
Circle.java
The generated class will be stored as "classes\com\yyy\Circle.class". Sub-directories "com" and "yyy" were created
automatically with the -d option.
Let's write a test program to use this Circle class. Suppose that TestCircle.java (in default package) is saved
in d:\myTest.

How to Set CLASSPATH in Java


CLASSPATH: CLASSPATH is an environment variable which is used by Application ClassLoader to locate
and load the .class files. The CLASSPATH defines the path, to find third-party and user-defined classes that
are not extensions or part of Java platform. Include all the directories which contain .class files and JAR files
when setting the CLASSPATH.

You need to set the CLASSPATH if:

o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.

The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH has a directory name or
file name at the end. The following points describe what should be the end of the CLASSPATH.

o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the zip or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the directory that contains the class
files.
o If class files placed in a named package, the CLASSPATH ends with the directory that contains the root
package in the full package name, that is the first package in the full package name.

The default value of CLASSPATH is a dot (.). It means the only current directory searched. The default value
of CLASSPATH overrides when you set the CLASSPATH variable or using the -classpath command (for short
-cp). Put a dot (.) in the new setting if you want to include the current directory in the search path.

If CLASSPATH finds a class file which is present in the current directory, then it will load the class and use it,
irrespective of the same name class presents in another directory which is also included in the CLASSPATH.

If you want to set multiple classpaths, then you need to separate each CLASSPATH by a semicolon (;).

The third-party applications (MySQL and Oracle) that use the JVM can modify the CLASSPATH environment
variable to include the libraries they use. The classes can be stored in directories or archives files. The classes
of the Java platform are stored in rt.jar.

There are two ways to ways to set CLASSPATH: through Command Prompt or by setting Environment
Variable.

Let's see how to set CLASSPATH of MySQL database:


Step 1: Click on the Windows button and choose Control Panel. Select System.

Step 2: Click on Advanced System Settings.

Step 3: A dialog box will open. Click on Environment Variables.

Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a semicolon
(;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable name
as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector Java.jar;.;

Remember: Put ;.; at the end of the CLASSPATH.

Difference between PATH and CLASSPATH


PATH CLASSPATH

PATH is an environment variable. CLASSPATH is also an environment variable.

It is used by the operating system to find the It is used by Application ClassLoader to locate the .class file.
executable files (.exe).

You are required to include the directory You are required to include all the directories which contain .class and JAR
which contains .exe files.

PATH environment variable once set, cannot The CLASSPATH environment variable can be overridden by using the co
be overridden. cp or -CLASSPATH to both javac and java command.

How to Set CLASSPATH in Windows Using Command Prompt


Type the following command in your Command Prompt and press enter.

1. set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;

In the above command, The set is an internal DOS command that allows the user to change the variable
value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%) is an existing
environment variable. The semicolon is a separator, and after the (;) there is the PATH of rt.jar file.

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.

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

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();

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

Inside Parent Class


a=10
b=20
c=30
d=40
Inside Child Class
a=10
b=20
c=30
Importing Packages in java
In java, the import keyword used to import built-in and user-defined packages. When a package has

imported, we can refer to all the classes of that package using their name directly.

The import statement must be after the package statement, and before any other statement.

Using an import statement, we may import a specific class or all the classes from a package.

□ Using one import statement, we may import only one package or a class.

□ Using an import statement, we can not import a class directly, but it must be a part of a package.

□ A program may contain any number of import statements.

Importing specific class

Using an importing statement, we can import a specific class. The following syntax is employed to import a

specific class.

Syntax

import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.

Example

package myPackage;

import java.util.Scanner;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also importing a
class called Scanner from java.util package.

Importing all the classes

Using an importing statement, we can import all the classes of a package. To import all the classes of the

package, we use * symbol. The following syntax is employed to import all the classes of a package.

Syntax

import packageName.*;

Let's look at an import statement to import a built-in package.

Example

package myPackage;

import java.util.*;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

Random rand = new Random();

int num = rand.nextInt(100);

System.out.println("Randomly generated number " + num);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also importing all
the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.

□ The import statement imports only classes of the package, but not sub-packages and its classes.

□ We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-
package.

Consider the following import statement.

import java.util.*;

The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.

Interfaces:
In java, an interface is similar to a class, but it contains abstract methods and static final variables only.
The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only one
interface, but a class may implement any number of interfaces.
□ An interface is a container of abstract methods and static final variables.
□ An interface, implemented by a class. (class implements interface).
□ An interface may extend another interface. (Interface extends Interface).
□ An interface never implements another interface, or class.
□ A class may implement any number of interfaces.
□ We can not instantiate an interface.
□ Specifying the keyword abstract for interface methods is optional, it automatically added.
□ All the members of an interface are public by default.

Defining an interface in java


Defining an interface is similar to that of a class. We use the keyword interface to define an interface. All the
members of an interface are public by default. The following is the syntax for defining an interface.

Syntax
interface InterfaceName{
...
members declaration;
...
}

Let's look at an example code to define an interface.

Example

interface HumanInterfaceExample {

void learn(String str);


void work();

int duration = 10;

In the above code defines an interface HumanInterfaceExample that contains two abstract methods
learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example code, no
member is defined as public, but all are public automatically.
The above code automatically converted as follows.

Converted code

interface HumanInterfaceExample {

public abstract void learn(String str);


public abstract void work();

public static final int duration = 10;

In the next tutorial, we will learn how a class implements an interface to make use of the interface concept.

Implementing an Interface in java


In java, an interface is implemented by a class. The class that implements an interface must provide code
for all the methods defined in the interface, otherwise, it must be defined as an abstract class.

The class uses a keyword implements to implement an interface. A class can implement any number of

interfaces. When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.

The following is the syntax for defineing a class that implements an interface.

Syntax

class className implements InterfaceName{


...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements an interface.

Example

interface Human {

void learn(String str);


void work();

int duration = 10;

class Programmer implements Human{


public void learn(String str) {
System.out.println("Learn using " + str);
}
public void work() {
System.out.println("Develop applications");
}
}

public class HumanTest {

public static void main(String[] args) {


Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}

In the above code defines an interface Human that contains two abstract methods learn(), work() and one constant

duration. The class Programmer implements the interface. As it implementing the Human interface it must provide the

body of all the methods those defined in the Human interface.

Implementing multiple Interfaces

When a class wants to implement more than one interface, we use the implements keyword is followed by
a comma-separated list of the interfaces implemented by the class.

The following is the syntax for defineing a class that implements multiple interfaces.

Syntax

class className implements InterfaceName1, InterfaceName2, ...{


...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements multiple interfaces.

Example

interface Human {
void learn(String str);
void work();
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
}
}

In the above code defines two interfaces Human and Recruitment, and a class Programmer implements both the

interfaces.
When we run the above program, it produce the following output.
Learn using coding
Attend Screening test
Attend Interview
Develop Applications

Extending an Interface in java


In java, an interface can extend another interface. When an interface wants to extend another interface, it
uses the keyword extends. The interface that extends another interface has its own members and all the

members defined in its parent interface too. The class which implements a child interface needs to provide
code for the methods defined in both child and parent interfaces, otherwise, it needs to be defined as

abstract class.

□ An interface can extend another interface.

□ An interface can not extend multiple interfaces.

□ An interface can implement neither an interface nor a class.

□ The class that implements child interface needs to provide code for all the methods defined in both child

and parent interfaces.


Let's look at an example code to illustrate extending an interface.

Example

interface ParentInterface{
void parentMethod();
}

interface ChildInterface extends ParentInterface{


void childMethod();
}

class ImplementingClass implements ChildInterface{

public void childMethod() {


System.out.println("Child Interface method!!");
}

public void parentMethod() {


System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingAnInterface {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.childMethod();
obj.parentMethod();

When we run the above program, it produce the following output.


Child Interface Method!
Parent Interface Method!

Nested Interfaces in java


In java, an interface may be defined inside another interface, and also inside a class. The interface that

defined inside another interface or a class is konwn as nested interface. The nested interface is also
refered as inner interface.

□ The nested interface declared within an interface is public by default.

□ The nested interface declared within a class can be with any access modifier.

□ Every nested interface is static by default.

The nested interface cannot be accessed directly. We can only access the nested interface by using outer

interface or outer class name followed by dot( . ), followed by the nested interface name.

Nested interface inside another interface

The nested interface that defined inside another interface must be accessed
as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.

Example

interface OuterInterface{
void outerMethod();

interface InnerInterface{
void innerMethod();
}
}

class OnlyOuter implements OuterInterface{


public void outerMethod() {
System.out.println("This is OuterInterface method");
}
}

class OnlyInner implements OuterInterface.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}

public class NestedInterfaceExample {

public static void main(String[] args) {


OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

obj_1.outerMethod();
obj_2.innerMethod();
}

When we run the above program, it produce the following output.


This is Outer Interface Method
This is Inner Interface Method
Variables in Java Interfaces
In java, an interface is a completely abstract class. An interface is a container of abstract methods and

static final variables. The interface contains the static final variables. The variables defined in an interface
can not be modified by the class that implements the interface, but it may use as it defined in the interface.

□ The variable in an interface is public, static, and final by default.

□ If any variable in an interface is defined without public, static, and final keywords then, the compiler
automatically adds the same.

□ No access modifier is allowed except the public for interface variables.

□ Every variable of an interface must be initialized in the interface itself.

□ The class that implements an interface can not modify the interface variable, but it may use as it defined

in the interface.

Let's look at an example code to illustrate variables in an interface.

Example

interface SampleInterface{

int UPPER_LIMIT = 100;

//int LOWER_LIMIT; // Error - must be initialised

public class InterfaceVariablesExample implements SampleInterface{

public static void main(String[] args) {

System.out.println("UPPER LIMIT = " + UPPER_LIMIT);

// UPPER_LIMIT = 150; // Can not be modified


}
}

When we run the above program, it produce the following output.


UPPER LIMIT=100

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, 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 need to handle
exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest
of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we
perform exception handling, the rest of the statements will be executed. That is why we use exception
handling in Java
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors areOutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

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

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

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

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example


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

JavaExceptionExample.java

1. public class JavaExceptionExample{


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

Output:

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


rest of the code...

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

Common Scenarios of Java Exceptions


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

1) A scenario where ArithmeticException occurs

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


1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable

, performing any operation on the variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string

variable that has characters; converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

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


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

Exception Types:

exception is an event that occurs during the execution of a program and disrupts
the normal flow of the program's instructions. Bugs or errors that we don't want
and restrict our program's normal execution of code are referred to
as exceptions. In this section, we will focus on the types of exceptions in
Java and the differences between the two.

Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can
understand the reason of getting this error. It can be categorized into two broad
categories, i.e., checked exceptions and unchecked exception.

Checked Exception
Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler ensures
whether the programmer handles the exception or not. The programmer should
have to handle the exception; otherwise, the system has shown a compilation
error.

CheckedExceptionExample.java

1. import java.io.*;
2. class CheckedExceptionExample {
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt
");
6. int m;
7. while(( m = file_data.read() ) != -1) {
8. System.out.print((char)m);9.
}
10. file_data.close();
11. }
12. }

In the above code, we are trying to read the Hello.txt file and display its data or
content on the screen. The program throws the following exceptions:

1. The FileInputStream(File filename) constructor throws


the FileNotFoundException that is checked exception.
2. The read() method of the FileInputStream class throws the IOException.
3. The close() method also throws the IOException.

Output:
How to resolve the error?
There are basically two ways through which we can solve these errors.

1) The exceptions occur in the main method. We can get rid from these
compilation errors by declaring the exception in the main method using the
throws We only declare the IOException, not FileNotFoundException, because of
the child-parent relationship. The IOException class is the parent class of
FileNotFoundException, so this exception will automatically cover by IOException.
We will declare the exception in the following way:

1. class Exception{
2. public static void main(String args[]) throws IOException {
3. ...
4. ...
5. }

If we compile and run the code, the errors will disappear, and we will see the data
of the file.

2) We can also handle these exception using try-catch However, the way which
we have used above is not correct. We have to a give meaningful message for
each exception type. By doing that it would be easy to understand the error. We
will use the try-catch block in the following way:

Exception.java

1. import java.io.*;
2. class Exception{
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. try{
6. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/progr
ams/Hell.txt");
7. }catch(FileNotFoundException fnfe){
8. System.out.println("File Not Found!");9.
}
10. int m;
11. try{
12. while(( m = file_data.read() ) != -1) {
13. System.out.print((char)m);
14. }
15. file_data.close();
16. }catch(IOException ioe){
17. System.out.println("I/O error occurred: "+ioe);
18. }
19. }
20. }

We will see a proper error message "File Not Found!" on the console because
there is no such file in that location.
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn't handle or declare
it, the program would not give a compilation error. Usually, it occurs when the
user provides bad data during the interaction with the program.

Note: The RuntimeException class is able to resolve all the unchecked exceptions
because of the child-parent relationship.

UncheckedExceptionExample1.java

1. class UncheckedExceptionExample1 {
2. public static void main(String args[])
3. {
4. int postive = 35;
5. int zero = 0;
6. int result = positive/zero;
7. //Give Unchecked Exception here.
8. System.out.println(result);
9. }
10. }

In the above program, we have divided 35 by 0. The code would be compiled


successfully, but it will throw an ArithmeticException error at runtime. On dividing
a number by 0 throws the divide by zero exception that is a uncheck exception.

Output:
UncheckedException1.java

1. class UncheckedException1 {
2. public static void main(String args[])
3. {
4. int num[] ={10,20,30,40,50,60};
5. System.out.println(num[7]);
6. }
7. }

Output:

In the above code, we are trying to get the element located at position 7, but the
length of the array is 6. The code compiles successfully, but throws the
ArrayIndexOutOfBoundsException at runtime.

User-defined Exception
In Java, we already have some built-in exception classes like ArrayIndex
OutOfBounds Exception, NullPointer Exception, and Arithmetic Exception.
These exceptions are restricted to trigger on some predefined conditions. In Java,
we can write our own exception class by extends the Exception class. We can
throw our own exception on a particular condition using the throw keyword. For
creating a user-defined exception, we should have basic knowledge of the try-
catch block and throw keyword.
Let's write a Java program and create user-defined exception.

UserDefinedException.java

1. import java.util.*;
2. class UserDefinedException{
3. public static void main(String args[]){
4. try{
5. throw new NewException(5);6.
}
7. catch(NewException ex){
8. System.out.println(ex) ;9.
}
10. }
11. }
12. class NewException extends Exception{
13. int x;
14. NewException(int y) {
15. x=y;
16. }
17. public String toString(){
18. return ("Exception value = "+x) ;
19. }
20. }

Output:
Description:

In the above code, we have created two classes, i.e., UserDefined


Exception and New Exception. The UserDefined Exception has our main
method, and the New Exception class is our user-defined exception class, which
extends exception. In the New Exception class, we create a variable x of type
integer and assign a value to it in the constructor. After assigning a value to that
variable, we return the exception message.

In the UserDefined Exception class, we have added a try-catch block. In the try
section, we throw the exception, i.e., New Exception and pass an integer to it.
The value will be passed to the NewException class and return a message. We
catch that message in the catch block and show it on the screen.

Difference Between Checked and Unchecked


Exception
S.No Checked Exception Unchecked Exception

1. These exceptions are checked at These exceptions are just opposite


compile time. These exceptions to the checked exceptions. These
are handled at compile time too. exceptions are not checked and
handled at compile time.

2. These exceptions are direct They are the direct subclasses of


subclasses of exception but not the RuntimeException class.
extended from RuntimeException
class.

3. The code gives a compilation The code compiles without any


error in the case when a method error because the exceptions
throws a checked exception. The escape the notice of the compiler.
compiler is not able to handle the These exceptions are the results of
exception on its own. user-created errors in programming
logic.

4. These exceptions mostly occur These exceptions occur mostly due


when the probability of failure is to programming mistakes.
too high.

5. Common checked exceptions Common unchecked exceptions


include IOException, include ArithmeticException,
DataAccessException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.

6. These exceptions are propagated These are automatically


using the throws keyword. propagated.

7. It is required to provide the try- In the case of unchecked exception


catch and try-finally block to it is not mandatory.
handle the checked exception.

Bugs or errors that we don't want and restrict the normal execution of the
programs are referred to as exceptions.

ArithmeticException,ArrayIndexOutOfBoundExceptions,ClassNotFoundExce
ptions etc. are come in the category of Built-in Exception. Sometimes, the built-
in exceptions are not sufficient to explain or describe certain situations. For
describing these situations, we have to create our own exceptions by creating an
exception class as a subclass of the Exception class. These types of exceptions
come in the category of User-Defined Exception.
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


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

Syntax of try-finally block


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

Java catch block


Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch
block with a single try block.
Internal Working of Java try-catch block

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

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

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

Problem without exception handling


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

Example 1
TryCatchExample1.java

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.

Solution by exception handling


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

Example 2
TryCatchExample2.java

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Output:
java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest
of the code statement is printed.

Example 3
In this example, we also kept the code in a try block that will not throw an
exception.

TryCatchExample3.java

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
Output:
java.lang.ArithmeticException: / by zero

Here, we can see that if an exception occurs in the try block, the rest of the block
code will not execute.

Example 4
Here, we handle the exception using the parent class exception.

TryCatchExample4.java

public class TryCatchExample4 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");

16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:
Arithmetic Exception occurs
rest of the code

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as
nested try block. Every statement that we enter a statement in try block, context
of that exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can
handle the ArithemeticException (division by zero).

Why use nested try block


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

Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two
different exceptions.

NestedTryBlock.java

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }

Output:
When any try block does not have a catch block for a particular exception, then
the catch block of the outer (parent) try block are checked for that exception, and
if it matches, the catch block of outer try block is executed.

If none of the catch block specified in the code is unable to handle the exception,
then the Java runtime system will handle the exception. Then it displays the
system generated message for that exception.

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom
exceptions making the code recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be
related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword.


It is mainly used to throw a custom exception. We will discuss custom exceptions
later in this section.

We can also define our own set of conditions and throw an exception explicitly
using throw keyword. For example, we can throw ArithmeticException if we divide
a number by another number. Here, we just need to set the condition and throw
exception using throw keyword.
The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

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

Where the Instance must be of type Throwable or subclass of Throwable. For


example, Exception is the sub class of Throwable and the user-defined exceptions
usually extend the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an
integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");7.
}
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:

The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the


exception or declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the


exception using catch block or the method must declare it using throws
declaration.

throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions
to handle. A method can do so by using the throws keyword.

Syntax :

type method_name(parameter_list) throws exception_list


{
//definition of method
}

NOTE : It is necessary for all exceptions, except the exceptions of


type Error and RuntimeException, or any of their subclass.

Example demonstrating throws Keyword

class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes whether or not exception has occurred. Using a finally block, lets you
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 catch block.

Example demonstrating finally Clause

Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Output :

Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound
exception.

You can see in above example even if exception is thrown by the program, which is not
handled by catch block, still finally block will get executed.

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom exception or
user-defined exception. Basically, Java custom exceptions are used to customize
the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception


class.

Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception class
that can be obtained using getMessage() method on the object we have created.

In this section, we will learn how custom exceptions are implemented and used in
Java programs.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in
the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

o To catch and provide specific treatment to a subset of existing Java


exceptions.
o Business logic exceptions: These are the exceptions related to business logic
and workflow. It is useful for the application users or the developers to
understand the exact problem.

In order to create custom exception, we need to extend Exception class that


belongs to java.lang package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }
Note: We need to write the constructor that takes the String as the error message and
it is called parent class constructor.

Example 1:
Let's see a simple example of Java custom exception. In the following code,
constructor of InvalidAgeException takes a string as an argument. This string is
passed to constructor of parent class Exception using the super() method. Also
the constructor of Exception class can be called without using a parameter and
calling super() method is not mandatory.

TestCustomException1.java
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10.
11. // class that uses custom exception InvalidAgeException
12. public class TestCustomException1
13. {
14.
15. // method to check the age
16. static void validate (int age) throws InvalidAgeException{
17. if(age < 18){
18.
19. // throw an object of user defined exception
20. throw new InvalidAgeException("age is not valid to vote");
21. }
22. else {
23. System.out.println("welcome to vote");
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45. }

Output:
Stream based I/O:

ByteStream Classes in Java


ByteStream classes are used to read bytes from the input stream and write bytes
to the output stream. In other words, we can say that ByteStream classes
read/write the data of 8-bits. We can store video, audio, characters, etc., by using
ByteStream classes. These classes are part of the java.io package.

The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the
Input/Output stream classes.

InputStream Class
The InputStream class provides methods to read bytes from a file, console or
memory. It is an abstract class and can't be instantiated; however, various classes
inherit the InputStream class and override its methods. The subclasses of
InputStream class are given in the following table.

SN Class Description

1 BufferedInputStream This class provides methods to read bytes from


the buffer.

2 ByteArrayInputStream This class provides methods to read bytes from


the byte array.

3 DataInputStream This class provides methods to read Java


primitive data types.

4 FileInputStream This class provides methods to read bytes from a


file.
5 FilterInputStream This class contains methods to read bytes from
the other input streams, which are used as the
primary source of data.

6 ObjectInputStream This class provides methods to read objects.

7 PipedInputStream This class provides methods to read from a piped


output stream to which the piped input stream
must be connected.

8 SequenceInputStream This class provides methods to connect multiple


Input Stream and read data from them.

The InputStream class contains various methods to read the data from an input
stream. These methods are overridden by the classes that inherit the InputStream
class. However, the methods are given in the following table.

Play Videox

SN Method Description

1 int read() This method returns an integer, an integral


representation of the next available byte of the input.
The integer -1 is returned once the end of the input is
encountered.

2 int read (byte This method is used to read the specified buffer length
buffer []) bytes from the input and returns the total number of
bytes successfully read. It returns -1 once the end of the
input is encountered.

3 int read (byte This method is used to read the 'nBytes' bytes from the
buffer [], int buffer starting at a specified location, 'loc'. It returns the
loc, int nBytes) total number of bytes successfully read from the input.
It returns -1 once the end of the input is encountered.

4 int available () This method returns the number of bytes that are
available to read.

5 Void mark(int This method is used to mark the current position in the
nBytes) input stream until the specified nBytes are read.

6 void reset () This method is used to reset the input pointer to the
previously set mark.

7 long skip (long This method is used to skip the nBytes of the input
nBytes) stream and returns the total number of bytes that are
skipped.

8 void close () This method is used to close the input source. If an


attempt is made to read even after the closing,
IOException is thrown by the method.
OutputStream Class
The OutputStream is an abstract class that is used to write 8-bit bytes to the
stream. It is the superclass of all the output stream classes. This class can't be
instantiated; however, it is inherited by various subclasses that are given in the
following table.

SN Class Description

1 BufferedOutputStream This class provides methods to write the bytes


to the buffer.

2 ByteArrayOutputStream This class provides methods to write bytes to


the byte array.

3 DataOutputStream This class provides methods to write the java


primitive data types.

4 FileOutputStream This class provides methods to write bytes to a


file.

5 FilterOutputStream This class provides methods to write to other


output streams.

6 ObjectOutputStream This class provides methods to write objects.

7 PipedOutputStream It provides methods to write bytes to a piped


output stream.

8 PrintStream It provides methods to print Java primitive data


types.
The OutputStream class provides various methods to write bytes to the output
streams. The methods are given in the following table.

SN Method Description

1 void write (int i) This method is used to write the specified single
byte to the output stream.

2 void write (byte It is used to write a byte array to the output


buffer [] ) stream.

3 Void write(bytes It is used to write nByte bytes to the output stream


buffer[],int loc, int from the buffer starting at the specified location.
nBytes)

4 void flush () It is used to flush the output stream and writes the
pending buffered bytes.

5 void close () It is used to close the output stream. However, if


we try to close the already closed output stream,
the IOException will be thrown by this method.

Example:
The following example uses the ByteArrayInputStream
to create an input stream from a byte array "content". We use the read() method to read the content from an input
stream. We have also used the write() method on a FileOutputStream object to write the byte array content in the file.

Consider the following example.


import java.io.ByteArrayInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputOutputStreamExample {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byte content[] = "Jtp is the best website to learn new technologies".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content);
File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content);
}
}

Output:
A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best
website to learn new technologies".

CharacterStream Classes in Java


The java.io package provides CharacterStream classes to overcome the limitations
of ByteStream classes, which can only handle the 8-bit bytes and is not
compatible to work directly with the Unicode characters. CharacterStream classes
are used to work with 16-bit Unicode characters. They can perform operations on
characters, char arrays and Strings.

However, the CharacterStream classes are mainly used to read characters from
the source and write them to the destination. For this purpose, the
CharacterStream classes are divided into two types of classes, I.e., Reader class
and Writer class.
Reader Class
Reader class
is used to read the 16-bit characters from the input stream. However, it is an abstract class and can't be instantiated, but
there are various subclasses that inherit the Reader class and override the methods of the Reader class. All methods of
the Reader class throw an IOException. The subclasses of the Reader class are given in the following table.

SN Class Description

1. BufferedReader This class provides methods to read characters from


the buffer.

2. CharArrayReader This class provides methods to read characters from


the char array.

3. FileReader This class provides methods to read characters from


the file.

4. FilterReader This class provides methods to read characters from


the underlying character input stream.

5 InputStreamReader This class provides methods to convert bytes to


characters.

6 PipedReader This class provides methods to read characters from


the connected piped output stream.

7 StringReader This class provides methods to read characters from


a string.

The Reader class methods are given in the following table.


SN Method Description

1 int read() This method returns the integral representation of the


next character present in the input. It returns -1 if the
end of the input is encountered.

2 int read(char This method is used to read from the specified buffer.
buffer[]) It returns the total number of characters successfully
read. It returns -1 if the end of the input is
encountered.

3 int read(char This method is used to read the specified nChars from
buffer[], int loc, the buffer at the specified location. It returns the total
int nChars) number of characters successfully read.

4 void mark(int This method is used to mark the current position in


nchars) the input stream until nChars characters are read.

5 void reset() This method is used to reset the input pointer to the
previous set mark.

6 long skip(long This method is used to skip the specified nChars


nChars) characters from the input stream and returns the
number of characters skipped.

7 boolean ready() This method returns a boolean value true if the next
request of input is ready. Otherwise, it returns false.

8 void close() This method is used to close the input stream.


However, if the program attempts to access the input,
it generates IOException.

Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream. The
methods of the Writer class generate IOException. Like Reader class, Writer class
is also an abstract class that cannot be instantiated; therefore, the subclasses of
the Writer class are used to write the characters onto the output stream. The
subclasses of the Writer class are given in the below table.

SN Class Description

1 BufferedWriter This class provides methods to write characters to


the buffer.

2 FileWriter This class provides methods to write characters to


the file.

3 CharArrayWriter This class provides methods to write the characters


to the character array.

4 OutpuStreamWriter This class provides methods to convert from bytes


to characters.

5 PipedWriter This class provides methods to write the characters


to the piped output stream.

6 StringWriter This class provides methods to write the characters


to the string.
To write the characters to the output stream, the Write class provides various
methods given in the following table.

SN Method Description

1 void write() This method is used to write the data to the output
stream.

2 void write(int i) This method is used to write a single character to the


output stream.

3 Void write(char This method is used to write the array of characters


buffer[]) to the output stream.

4 void write(char This method is used to write the nChars characters to


buffer [],int loc, int the character array from the specified location.
nChars)

5 void close () This method is used to close the output stream.


However, this generates the IOException if an
attempt is made to write to the output stream after
closing the stream.

6 void flush () This method is used to flush the output stream and
writes the waiting buffered characters.
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.

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, It provides a formatted prompt then reads the
Object... args) 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 It provides a formatted prompt then reads the


fmt, Object... args) password that is not being displayed on the
console.

Console format(String fmt, It is used to write a formatted string


Object... args)
to the console output stream.

Console printf(String format, It is used to write a string to the console output


Object... 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();
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
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.

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 It creates a new File instance from a parent abstract
child) 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, It creates a new File instance from a parent pathname


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

Useful Methods
Modifier Method Description
and Type

static File createTempFile(String It creates an empty file in the default


prefix, String suffix) temporary-file directory, using the
given prefix and suffix to generate its
name.

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 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(FilenameFilter filter) It returns an array of strings naming


the files and directories 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


1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }

Output:
New File is created!

Java File Writer Class


Java FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java.

Unlike FileOutputStream class, you don't need to convert string into


byte array because it provides method to write string directly.

Java File Writer class declaration


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

1. public class FileWriter extends OutputStreamWriter

Constructors of File Writer class


Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.
Methods of File Writer class
Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Java File Writer Example


In this example, we are writing the data in the file testout.txt using Java FileWriter
class.

1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javapoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }
Output:
Success...

testout.txt:
Welcome to javapoint.

Java File Reader Class


Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.

It is character-oriented class which is used for file handling in java.

Java FileReader class declaration


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

1. public class FileReader extends InputStreamReader

Constructors of File Reader class


Constructor Description

FileReader(String It gets filename in string. It opens the given file in read


file) mode. If file doesn't exist, it throws FileNotFoundException.

FileReader(File It gets filename in file instance. It opens the given file in


file) read mode. If file doesn't exist, it throws
FileNotFoundException.
Methods of File Reader class
Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the


end of file.

void It is used to close the FileReader class.


close()

Java File Reader Example


In this example, we are reading the data from the text file testout.txt using Java
FileReader class.

1. package com.javatpoint;
2. import java.io.FileReader;
3. public class FileReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.print((char)i);
9. fr.close();
10. }
11. }

Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.

Output:
Welcome to javaTpoint.
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


file, String from, and optionally to write to, the file
specified by the File argument.
mode)

RandomAccessFile(String Creates a random access file stream to read


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

Method
Modifier Method Method
and Type

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 pos) It sets the file-pointer offset, measured


from the beginning of this file, at which
the next read or write occurs.

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


v) using the doubleToLongBits method in
class Double, and then writes that long
value to the file as an eight-byte quantity,
high byte first.

void writeFloat(float v) It converts the float argument to an int


using the floatToIntBits 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 pos) It sets the file-pointer offset, measured


from the beginning of this file, at which
the next read or write occurs.

Example

1. import java.io.IOException;

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

This class is used for reading I love my country and my people.

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.

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, It provides a formatted prompt then reads the


Object... args) 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 It provides a formatted prompt then reads the


fmt, Object... args) password that is not being displayed on the
console.

Console format(String fmt, It is used to write a formatted string


Object... args)
to the console output stream.

Console printf(String format, It is used to write a string to the console output


Object... 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();
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 and Deserialization in Java


Serialization in Java is a mechanism of writing the state of an object into a byte-
stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream


is converted into an object. The serialization and deserialization process is
platform-independent, it means you can serialize an object on one platform and
deserialize it on a different platform.

For serializing the object, we call the writeObject() method


of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.
Advantages of Java Serialization
It is mainly used to travel object's state on the network (that is known as
marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain
capability. The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs
to be persisted.

The String class and all the wrapper classes implement


the java.io.Serializable interface by default.

Let's see the example given below:

Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements Serializable interface. Now its
objects can be converted into stream. The main class implementation of is
showed in the next code.

ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java
objects to an OutputStream. Only objects that support the java.io.Serializable
interface can be written to streams.

Constructor

1) public It creates an ObjectOutputStream


ObjectOutputStream(OutputStream out) that writes to the specified
throws IOException {} OutputStream.

Important Methods

Method Description

1) public final void writeObject(Object It writes the specified object to the


obj) throws IOException {} ObjectOutputStream.

2) public void flush() throws It flushes the current output stream.


IOException {}

3) public void close() throws It closes the current output stream.


IOException {}
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream It creates an ObjectInputStream


in) throws IOException {} that reads from the specified
InputStream.

Important Methods

Method Description

1) public final Object readObject() throws It reads an object from the


IOException, ClassNotFoundException{} input stream.

2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above
code. The writeObject() method of ObjectOutputStream class provides the
functionality to serialize the object. We are saving the state of the object in the
file named f.txt.

Persist.java

1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

Output:
success

Example of Java Deserialization


Deserialization is the process of reconstructing the object from the serialized
state. It is the reverse operation of serialization. Let's see an example where we
are reading the data from a deserialized object.

Deserialization is the process of reconstructing the object from the serialized


state. It is the reverse operation of serialization. Let's see an example where we
are reading the data from a deserialized object.

Depersist.java

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Output:
211 ravi

Java Enums
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{
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").ordina
l());
12. System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordi
nal());
13.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.
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.

Defining Java Enum


The enum can be defined within or outside the class because it is similar to a
class. The semicolon (;) at the end of the enum constants are optional. For
example:

1. enum Season { WINTER, SPRING, SUMMER, FALL }

Or,

1. enum Season { WINTER, SPRING, SUMMER, FALL; }

Both the definitions of Java enum are the same.

Java Enum Example: Defined outside class


1. enum Season { WINTER, SPRING, SUMMER, FALL }
2. class EnumExample2{
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }}
Output:
WINTER

Java Enum Example: Defined inside class


1. class EnumExample3{
2. enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
3. public static void main(String[] args) {
4. Season s=Season.WINTER;//enum type is required to access WINTER
5. System.out.println(s);
6. }}

Output:
WINTER

Java Enum Example: main method inside Enum


If you put main() method inside the enum, you can run the enum directly.

1. enum Season {
2. WINTER, SPRING, SUMMER, FALL;
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }
7. }

Output:
WINTER

Initializing specific values to the enum constants


The enum constants have an initial value which starts from 0, 1, 2, 3, and so on.
But, we can initialize the specific value to the enum constants by defining fields
and constructors. As specified earlier, Enum can have fields, constructors, and
methods.
Example of specifying initial value to the enum constants
1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4.
5. private int value;
6. private Season(int value){
7. this.value=value;
8. }
9. }
10. public static void main(String args[]){
11. for (Season s : Season.values())
12. System.out.println(s+" "+s.value);
13.
14. }}
15.

Output:
WINTER 5
SPRING 10
SUMMER 15
FALL 20

Constructor of enum type is private. If you don't declare private compiler internally
creates private constructor.
1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }
Internal code generated by the compiler for the above
example of enum type
1. final class Season extends Enum
2. {
3. public static Season[] values()
4. {
5. return (Season[])$VALUES.clone();
6. }
7. public static Season valueOf(String s)
8. {
9. return (Season)Enum.valueOf(Season, s);
10. }
11. private Season(String s, int i, int j)
12. {
13. super(s, i);
14. value = j;
15. }
16. public static final Season WINTER;
17. public static final Season SUMMER;
18. private int value;
19. private static final Season $VALUES[];
20. static
21. {
22. WINTER = new Season("WINTER", 0, 10);
23. SUMMER = new Season("SUMMER", 1, 20);
24. $VALUES = (new Season[] {
25. WINTER, SUMMER
26. });
27. }
28. }
Can we create the instance of Enum by new keyword?
No, because it contains private constructors only.

Can we have an abstract method in the Enum?


Yes, Of course! we can have abstract methods and can provide the
implementation of these methods.

Java Enum in a switch statement


We can apply enum on switch statement as in the given example:

Example of applying Enum on a switch statement

1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SA
TURDAY}
3. public static void main(String args[]){
4. Day day=Day.MONDAY;
5.
6. switch(day){
7. case SUNDAY:
8. System.out.println("sunday");
9. break;
10. case MONDAY:
11. System.out.println("monday");
12. break;
13. default:
14. System.out.println("other day");
15. }
16. }}

Output:
monday
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type
is known as boxing and opposite operation is known as unboxing. This is the new
feature of Java5. So java programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding
is required.

Simple Example of Autoboxing in java:


1.
2. class BoxingExample1{
3. public static void main(String args[]){
4. int a=50;
5. Integer a2=new Integer(a);//Boxing
6.
7. Integer a3=5;//Boxing
8.
9. System.out.println(a2+" "+a3);
10. }
11. }
12.
Output:50 5

Simple Example of Unboxing in java:


The automatic conversion of wrapper class type into corresponding primitive
type, is known as Unboxing. Let's see the example of unboxing:

1. class UnboxingExample1{
2. public static void main(String args[]){
3. Integer i=new Integer(50);
4. int a=i;
5.
6. System.out.println(a);
7. }
8. }
9.

Output:
50

Autoboxing and Unboxing with comparison operators


Autoboxing can be performed with comparison operators. Let's see the example
of boxing with comparison operator:

1.
2. class UnboxingExample2{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Output:50

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-
generic. Now generics force the java programmer to store a specific type of
objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t


allow to store other objects.

Without Generics, we can store any type of objects.

1. List list = new ArrayList();


2. list.add(10);
3. list.add("10");
4. With Generics, it is required to specify the type of object we need to store.
5. List<Integer> list = new ArrayList<Integer>();
6. list.add(10);
7. list.add("10");// compile-time error

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

1. List list = new ArrayList();


2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
4. After Generics, we don't need to typecast the object.
5. List<String> list = new ArrayList<String>();
6. list.add("hello");
7. String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not


occur at runtime. The good programming strategy says it is far better to handle
the problem at compile time than runtime.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. list.add(32);//Compile Time Error
Syntax to use generic collection

1. ClassOrInterface<Type>

Example to use Generics in java

1. ArrayList<String>

Full Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Output:
element is: jai
rahul
jai

Generic class
A class that can refer to any type is known as a generic class. Here, we are using
the T type parameter to create the generic class of specific type.

Let's see a simple example to create and use the generic class.

Creating a generic class:


1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, and
Employee). The type you specify for the class will be used to store and retrieve
the data.

Using generic class:

Let's see the code to use the generic class.

1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}

Output
2
UNIT-IV Multi Threading
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs


in a single thread.

Thread Concept in Java


Before introducing the thread concept, we were unable to run more than one task
in parallel. It was a drawback, and to remove that drawback, Thread Concept was
introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.

In order to perform complicated tasks in the background, we used the Thread


concept in Java. All the tasks are executed without affecting the main program. In a
program or process, all the threads have their own separate path for execution, so
each thread of a process is independent.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 1


Another benefit of using thread is that if a thread gets an exception or an error at
the time of its execution, it doesn't affect the execution of the other threads. All the
threads share a common memory and have their own stack, local variables and
program counter. When multiple threads are executed in parallel at the same time,
this process is known as Multithreading

In a simple way, a Thread is a:

o Feature through which we can perform multiple activities within a single


process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Thread Model
Just like a process, a thread exists in several states. These states are as follows:

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 2


1) New (Ready to run)
A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under
execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread

A thread is created either by "creating or implementing" the Runnable Interface or


by extending the Thread class. These are the only two ways through which we can
create a thread.

Let's dive into details of both these way of creating a thread:

Thread Class

A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long
stackSize)

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 3


Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose instances


are intended to be executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.

start() method

The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.

Let's take an example to understand how we can create a Java


thread by extending the Thread class:

ThreadExample1.java

// Implementing runnable interface by extending Thread class


public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 4
}
}

Output:

Creating thread by implementing the runnable interface

In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.

Let's takes an example to understand how we can create, start and run the thread
using the runnable interface.

ThreadExample2.java

class NewThread implements Runnable {


String name;
Thread thread;
NewThread (String name){
this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread+ "is created\n" );
thread.start();
}
public void run() {
try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 5
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException excetion) {
System.out.println("Inturruption occurs in Main Thread");
}
System.out.println("We are exiting from Main Thread");
}
}

Output:

In the above example, we perform the Multithreading by implementing the runnable


interface.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 6


How to create a thread in Java
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

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

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public int getPriority(): returns the priority of the thread.
4. public int setPriority(int priority): changes the priority of the thread.
5. public String getName(): returns the name of the thread.
6. public void setName(String name): changes the name of the thread.
7. public void suspend(): is used to suspend the thread(depricated).
8. public void resume(): is used to resume the suspended thread(depricated).
9. public void stop(): is used to stop the thread(depricated).
10. public void interrupt(): interrupts the thread.

Runnable interface:
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 7
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

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

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class

FileName: Multi.java

class Multi extends Thread{


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

Output:
thread is running...

Java Thread Example by implementing Runnable interface

FileName: Multi3.java

class Multi3 implements Runnable{


B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 8
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:
thread is running...

If you are not extending the Thread class, your class object would not be treated as
a thread object. So you need to explicitly create the Thread class object. We are
passing the object of your class that implements Runnable so that your class run()
method may execute.
Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors
defined above.

FileName: MyThread1.java

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 9
String str = t.getName();
System.out.println(str);
}
}

Output:
My first thread

Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

public class MyThread2 implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ...");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 10


}

Output:
My new thread
Now the thread is running ...

Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority

Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the


priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority()


method updates or assign the priority of the thread to newPriority. The method
throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

FileName: ThreadPriority.java

// Importing the required classes


B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 11
import java.lang.*;
public class ThreadPriority extends Thread
{
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String args[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriority th1 = new ThreadPriority();
ThreadPriority th2 = new ThreadPriority();
ThreadPriority th3 = new ThreadPriority();
// We did not mention the priority of the thread.
// Therefore, the priorities of the thread is 5, the default value
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// Setting priorities of above threads by
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 12
// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().get
Name());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
}
}

Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

We know that a thread with high priority will get preference over lower priority
threads when it comes to the execution of threads. However, there can be other

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 13


scenarios where two threads can have the same priority. All of the processing, in
order to look after the threads, is done by the Java thread scheduler. Refer to the
following example to comprehend what will happen if two threads have the same
priority.

FileName: ThreadPriorityExample1.java

// importing the java.lang package


import java.lang.*;
public class ThreadPriorityExample1 extends Thread
{
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String argvs[])
{
// Now, priority of the main thread is set to 7
Thread.currentThread().setPriority(7);
// the current thread is retrieved
// using the currentThread() method
// displaying the main thread priority
// using the getPriority() method of the Thread class
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());

// creating a thread by creating an object of the class ThreadPriorityExample1

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 14


ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
// th1 thread is the child of the main thread
// therefore, the th1 thread also gets the priority 7
// Displaying the priority of the current thread
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
}
}

Output:
Priority of the main thread is : 7
Priority of the thread th1 is : 7

Explanation: If there are two threads that have the same priority, then one can not
predict which thread will get the chance to execute first. The execution then is
dependent on the thread scheduler's algorithm (First Come First Serve, Round-
Robin, etc.)

Example of IllegalArgumentException
We know that if the value of the parameter newPriority of the method getPriority()
goes out of the range (1 to 10), then we get the IllegalArgumentException. Let's
observe the same with the help of an example.

FileName: IllegalArgumentException.java

// importing the java.lang package


import java.lang.*;
public class IllegalArgumentException extends Thread
{
// the main method
public static void main(String argvs[])
{
// Now, priority of the main thread is set to 17, which is greater than 10
Thread.currentThread().setPriority(17);
// The current thread is retrieved

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 15


// using the currentThread() method
// displaying the main thread priority
// using the getPriority() method of the Thread class
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
}
}

When we execute the above program, we get the following exception:


Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1141)
at IllegalArgumentException.main(IllegalArgumentException.

Synchronization in Java

Synchronization in Java is the capability to control the access of multiple threads to


any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 16


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

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

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor.


Every object has a lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the


example:

TestSynchronization1.java

class Table{
void printTable(int n){//method not synchronized
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 17
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 18
t1.start();
t2.start();
}
}

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

Java Synchronized Method

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

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

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

TestSynchronization2.java

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 19
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }
Output:

5
10
15
20
25
100
200

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 20


300
400
500

Example of synchronized method by using annonymous class

In this program, we have created the two threads by using the anonymous class, so
less coding is required.

TestSynchronization3.java

//Program of synchronized method by using annonymous class


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
public class TestSynchronization3{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 21


};
t1.start();
t2.start();
}
}

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

Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed. It is implemented by following methods
of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 22


Method Description

public final void wait()throws It waits until object is notified.


InterruptedException

public final void wait(long timeout)throws It waits for the specified


InterruptedException amount of time.

2) notify() method

The notify() method wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.

Syntax:

1. public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 23


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the
lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or After the specified amount of time,


notifyAll() methods sleep is completed.

Example of Inter Thread Communication in Java


B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 24
Let's see the simple example of inter thread communication.

Test.java

class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 25
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

The Collections Framework (java.util):


Collections Overview:

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.

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

Hierarchy of Collection Framework

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 26


Let us see the hierarchy of Collection framework. The java.util package contains all the classes and interfaces for
the Collection framework.

Collection Interface
The Collection interface is the root interface of the Java collections framework.
There is no direct implementation of this interface. However, it is implemented
through its subinterfaces like List, Set, and Queue.

For example, the ArrayList class implements the List interface which is a
subinterface of the Collection Interface.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 27


Sub interfaces of Collection
As mentioned above, the Collection interface includes sub interfaces that are implemented by

various classes in Java.

1. List Interface
The List interface is an ordered collection that allows us to add and remove elements like an

array.

2. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It

cannot have duplicate elements.

3. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out

(FIFO) manner.

Collection Classes:
Array List:

Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the java.util package. It is like
the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It


implements the List interface so we can use all the methods of the
List interface here. The ArrayList maintains the insertion order
internally.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 28


o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because the array works on an index basis.
o In ArrayList, manipulation is a little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from the
array list.
o We can not create an array list of the primitive types, such as int, float, char,
etc. It is required to use the required wrapper class in such cases. For example:

1. ArrayList<int> al = ArrayList<int>(); // does not work


2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
o Java ArrayList gets initialized by the size. The size is dynamic in the array list,
which varies according to the elements getting added or removed from the list.

Hierarchy of ArrayList class

As shown in the above diagram, the Java ArrayList class extends AbstractList class
which implements the List interface. The List interface extends the Collection and
Iterable interfaces in hierarchical order.

ArrayList class declaration


Let's see the declaration for java.util.ArrayList class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAc


cess, Cloneable, Serializable

Constructors of ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? It is used to build an array list that is initialized

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 29


extends E> c) with the elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the


specified initial capacity.

Methods of ArrayList

Method Description

void add(int index, E element) It is used to insert the specified element at


the specified position in a list.

boolean add(E e) It is used to append the specified element


at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements in


extends E> c) the specified collection to the end of this
list, in the order that they are returned by
the specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the


Collection<? extends E> c) specified collection, starting at the specified
position of the list.

void clear() It is used to remove all of the elements


from this list.

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 30
Java new generic collection allows you to have only one type of object in a
collection. Now it is type-safe, so typecasting is not required at runtime.

Let's see the old non-generic example of creating a Java collection.

1. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced
to have the only specified type of object in it. If you try to add another type of
object, it gives a compile-time error.

For more information on Java generics, click here Java Generics Tutorial.

Java ArrayList Example


FileName: ArrayListExample1.java

import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}

Output:
[Mango, Apple, Banana, Grapes]

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 31


Iterating ArrayList using Iterator
Let's see an example to traverse ArrayList elements using the Iterator interface.

FileName: ArrayListExample2.java

import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}

Output:
Mango
Apple
Banana
Grapes

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: ArrayListExample3.java

import java.util.*;
public class ArrayListExample3{

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 32


public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}

Output:
Mango
Apple
Banana
Grapes

Get and Set ArrayList


The get() method returns the element at the specified index, whereas the set()
method changes the element.

FileName: ArrayListExample4.java

import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 33


System.out.println("Returning element: "+al.get(1));//it will return the 2nd element,
because index starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}

Output:
Returning element: Apple
Mango
Dates
Banana
Grapes

Java Linked List class

Java LinkedList class uses a doubly linked list to store the elements. It provides a
linked-list data structure. It inherits the AbstractList class and implements List and
Deque interfaces.

The important points about Java LinkedList are:

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 34


o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class


As shown in the above diagram, Java LinkedList class extends AbstractSequentialList
class and implements List and Deque interfaces.

Doubly Linked List


In the case of a doubly linked list, we can add or remove elements from both sides.

LinkedList class declaration


Let's see the declaration for java.util.LinkedList class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>


, Deque<E>, Cloneable, Serializable

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the


extends E> c) elements of the specified collection, in the order,
they are returned by the collection's iterator.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 35


Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the


end of a list.

void add(int index, E It is used to insert the specified element at the


element) specified position index in a list.

boolean It is used to append all of the elements in the


addAll(Collection<? specified collection to the end of this list, in the
extends E> c) order that they are returned by the specified
collection's iterator.

boolean It is used to append all of the elements in the


addAll(Collection<? specified collection to the end of this list, in the
extends E> c) order that they are returned by the specified
collection's iterator.

boolean addAll(int index, It is used to append all the elements in the


Collection<? extends E> c) specified collection, starting at the specified
position of the list.

void addFirst(E e) It is used to insert the given element at the


beginning of a list.

void addLast(E e) It is used to append the given element to the end


of a list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

Java LinkedList Example


import java.util.*;

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 36


public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay

Java LinkedList example to add elements


Here, we see different ways to add elements.

import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 37
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method:
"+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c)
method: "+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);
}
}
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements


Here, we see different ways to remove an element.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 38


import java.util.*;
public class LinkedList3 {
public static void main(String [] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add("Anuj");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Virat");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 39
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);
//Removing all the elements available in the list
ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements


import java.util.*;
public class LinkedList4{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 40


ll.add("Vijay");
ll.add("Ajay");
//Traversing the list of elements in reverse order
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output: Ajay
Vijay
Ravi

Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 41


o HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class


The HashSet class extends AbstractSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration


Let's see the declaration for java.util.HashSet class.

1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,


Serializable

Constructors of Java HashSet class


SN Constructor Description

1) HashSet() It is used to construct a default HashSet.

2) HashSet(int capacity) It is used to initialize the capacity of the hash


set to the given integer value capacity. The
capacity grows automatically as elements are
added to the HashSet.

3) HashSet(int capacity, It is used to initialize the capacity of the hash


float loadFactor) set to the given integer value capacity and the

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 42


specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the


extends E> c) elements of the collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

SN Modifier & Method Description


Type

1) boolean add(E e) It is used to add the specified element


to this set if it is not already present.

2) Void clear() It is used to remove all of the elements


from the set.

3) object clone() It is used to return a shallow copy of


this HashSet instance: the elements
themselves are not cloned.

4) boolean contains(Object It is used to return true if this set


o) contains the specified element.

5) boolean isEmpty() It is used to return true if this set


contains no elements.

6) Iterator<E> iterator() It is used to return an iterator over the

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 43


elements in this set.

Java HashSet Example


Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.

import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Five
One
Four
Two
Three

Java HashSet example ignoring duplicate elements


In this example, we see that HashSet doesn't allow duplicate elements.

import java.util.*;
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 44
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi

Java HashSet example to remove elements


Here, we see different ways to remove an element.

import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 45


set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

Java TreeSet class

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 46


Java TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements the NavigableSet interface. The objects of
the TreeSet class are stored in ascending order.

The important points about the Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quite fast.
o Java TreeSet class doesn't allow null elements.
o Java TreeSet class is non-synchronized.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 47


o Java TreeSet class maintains ascending order.
o The TreeSet can only allow those generic types that are comparable. For
example The Comparable interface is being implemented by the StringBuffer
class.

Internal Working of The TreeSet Class


TreeSet is being implemented using a binary search tree, which is self-balancing just
like a Red-Black Tree. Therefore, operations such as a search, remove, and add
consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It
is there to ensure that the tree height never exceeds O(log(N)) for all of the
mentioned operations. Therefore, it is one of the efficient data structures in order to
keep the large data that is sorted and also to do operations on it.

Synchronization of The TreeSet Class


As already mentioned above, the TreeSet class is not synchronized. It means if more
than one thread concurrently accesses a tree set, and one of the accessing threads
modify it, then the synchronization must be done manually. It is usually done by
doing some object synchronization that encapsulates the set. However, in the case
where no such object is found, then the set must be wrapped with the help of the
Collections.synchronizedSet() method. It is advised to use the method during
creation time in order to avoid the unsynchronized access of the set. The following
code snippet shows the same.

1. TreeSet treeSet = new TreeSet();


2. Set syncrSet = Collections.synchronziedSet(treeSet);

Hierarchy of TreeSet class


As shown in the above diagram, the Java TreeSet class implements the NavigableSet
interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable
interfaces in hierarchical order.

TreeSet Class Declaration


B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 48
Let's see the declaration for java.util.TreeSet class.

1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cl


oneable, Serializable

Constructors of Java TreeSet Class

Constructor Description

TreeSet() It is used to construct an empty tree set that


will be sorted in ascending order according to
the natural order of the tree set.

TreeSet(Collection<? extends It is used to build a new tree set that contains


E> c) the elements of the collection c.

TreeSet(Comparator<? super It is used to construct an empty tree set that


E> comparator) will be sorted according to given comparator.

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the


elements of the given SortedSet.

Methods of Java TreeSet Class

Method Description

boolean add(E e) It is used to add the specified element to


this set if it is not already present.

boolean addAll(Collection<? It is used to add all of the elements in


extends E> c) the specified collection to this set.

E ceiling(E e) It returns the equal or closest greatest


element of the specified element from
the set, or null there is no such element.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 49


Comparator<? super E> It returns a comparator that arranges
comparator() elements in order.

Iterator descendingIterator() It is used to iterate the elements in


descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

E floor(E e) It returns the equal or closest least


element of the specified element from
the set, or null there is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are


less than the specified element.

NavigableSet headSet(E toElement, It returns the group of elements that are


boolean inclusive) less than or equal to(if, inclusive is true)
the specified element.

E higher(E e) It returns the closest greatest element of


the specified element from the set, or
null there is no such element.

Iterator iterator() It is used to iterate the elements in


ascending order.

E lower(E e) It returns the closest least element of the


specified element from the set, or null
there is no such element.

E pollFirst() It is used to retrieve and remove the


lowest(first) element.

E pollLast() It is used to retrieve and remove the


highest(last) element.

Spliterator spliterator() It is used to create a late-binding and

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 50


fail-fast spliterator over the elements.

Java TreeSet Example 1:


FileName: TreeSet1.java

import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ajay
Ravi
Vijay

Java TreeSet Example 2:


Let's see an example of traversing elements in descending order.

FileName: TreeSet2.java

import java.util.*;

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 51


class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
System.out.println("Traversing element through Iterator in descending order");
Iterator i=set.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

Output:
Traversing element through Iterator in descending order
Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that gives us a
way for processing the objects on the basis of priority. It is already described that
the insertion and deletion of objects follows FIFO pattern in the Java queue.
However, sometimes the elements of the queue are needed to be processed
according to the priority, that's where a PriorityQueue comes into action.

PriorityQueue Class Declaration

Let's see the declaration for java.util.PriorityQueue class.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 52


public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Java PriorityQueue Example
FileName: TestCollection12.java

import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}

Output:

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 53


head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Java Deque Interface


The interface called Deque is present in java.util package. It is the subtype of the
interface queue. The Deque supports the addition as well as the removal of elements
from both ends of the data structure. Therefore, a deque can be used as a stack or a
queue. We know that the stack supports the Last In First Out (LIFO) operation, and
the operation First In First Out is supported by a queue. As a deque supports both,
either of the mentioned operations can be performed on it. Deque is an acronym
for "double ended queue".

Deque Interface declaration


1. public interface Deque<E> extends Queue<E>
Object Inserts the element e at the tail of the queue. If the insertion is
offerLast(e) successful, true is returned; otherwise, false.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 54


ArrayDeque class
We know that it is not possible to create an object of an interface in Java. Therefore,
for instantiation, we need a class that implements the Deque interface, and that class
is ArrayDeque. It grows and shrinks as per usage. It also inherits the
AbstractCollection class.

The important points about ArrayDeque class are:

o Unlike Queue, we can add or remove elements from both sides.


o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.

ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed at the right side of
the page.

ArrayDeque class declaration

Let's see the declaration for java.util.ArrayDeque class.

1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E


>, Cloneable, Serializable

Java ArrayDeque Example


FileName: ArrayDequeExample.java

import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Ravi");
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 55
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}

Output:
Ravi
Vijay
Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

FileName: DequeExample.java

import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 56


for(String s:deque){
System.out.println(s);
}
}
}

Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

Java Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of
the bucket is identified by calling the hashcode() method. A Hashtable contains
values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clo


neable, Serializable

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 57


Hashtable class Parameters
Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java Hashtable class

Constructor Description

Hashtable() It creates an empty hashtable having the initial


default capacity and load factor.

Hashtable(int capacity) It accepts an integer parameter and creates a


hash table that contains a specified initial
capacity.

Hashtable(int capacity, float It is used to create a hash table having the


loadFactor) specified initial capacity and loadFactor.

Hashtable(Map<? extends It creates a new hash table with the same


K,? extends V> t) mappings as the given Map.

Methods of Java Hashtable class

Method Description

void clear() It is used to reset the hash table.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 58


Object clone() It returns a shallow copy of the Hashtable.

V get(Object key) This method returns the object that contains the value
associated with the key.

V remove(Object It is used to remove the key and its value. This method
key) returns the value associated with the key.

int size() This method returns the number of entries in the hash
table.

Java Hashtable Example


import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 59


Java Hashtable Example: remove()

import java.util.*;
public class Hashtable2 {
public static void main(String args[]) {
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("After remove: "+ map);
}
}

Output:
Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
After remove: {103=Rahul, 101=Vijay, 100=Amit}

Java Hashtable Example: getOrDefault()

import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Here, we specify the if and else statement as arguments of the method
System.out.println(map.getOrDefault(101, "Not Found"));

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 60


System.out.println(map.getOrDefault(105, "Not Found"));
}
}

Output:
Vijay
Not Found

Java Hashtable Example: putIfAbsent()

import java.util.*;
class Hashtable4{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Initial Map: "+map);
//Inserts, as the specified pair is unique
map.putIfAbsent(104,"Gaurav");
System.out.println("Updated Map: "+map);
//Returns the current value, as the specified pair already exist
map.putIfAbsent(101,"Vijay");
System.out.println("Updated Map: "+map);
}
}

Output:
Initial Map: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 61


Properties class in Java

The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class
provides methods to get data from the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file


Recompilation is not required if the information is changed from a properties
file: If any information is changed from the properties file, you don't need to
recompile the java class. It is used to store information which is to be changed
frequently.

Constructors of Properties class

Method Description

Properties() It creates an empty property list with no default


values.

Properties(Properties It creates an empty property list with the


defaults) specified defaults.

Methods of Properties class


The commonly used methods of Properties class are given below.

Method Description

public void load(Reader r) It loads data from the Reader object.

public void load(InputStream is) It loads data from the InputStream object

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 62


Example of Properties class to get information from the properties file

To get information from the properties file, create the properties file first.

db.properties
1. user=system
2. password=oracle

Now, let's create the java class to read the data from the properties file.

Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle

Now if you change the value of the properties file, you don't need to recompile the
java class. That means no maintenance problem.

Example of Properties class to get all the system properties

By System.getProperties() method we can get all the properties of the system. Let's
create the class that gets information from the system properties.

Test.java
import java.util.*;
import java.io.*;

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 63


public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........

Java Stack Class

In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects. Before using the Stack class, we
must import the java.util package. The stack class arranged in the Collections
framework hierarchy, as shown below.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 64


Stack Class Constructor

The Stack class contains only the default constructor that creates an empty stack.

1. public Stack()
Creating a Stack

If we want to create a stack, first, import the java.util package and create an object of
the Stack class.

1. Stack stk = new Stack();

Or

1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class

We can perform push, pop, peek and search operation on the stack. The Java Stack
class provides mainly five methods to perform these operations. Along with this, it
also provides all the methods of the Java Vector class.

Method Modifier Method Description


and Type

empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto


the top of the stack.

pop() E The method removes an element from the top


of the stack and returns the same element as
the value of that function.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 65


peek() E The method looks at the top element of the
stack without removing it.

search(Object int The method searches the specified object and


o) returns the position of the object.

Stack Class empty() Method

The empty() method of the Stack class check the stack is empty or not. If the stack
is empty, it returns true, else returns false. We can also use the isEmpty() method of
the Vector class.

Syntax

1. public boolean empty()

Returns: The method returns true if the stack is empty, else returns false.

In the following example, we have created an instance of the Stack class. After that,
we have invoked the empty() method two times. The first time it
returns true because we have not pushed any element into the stack. After that, we
have pushed elements into the stack. Again we have invoked the empty() method
that returns false because the stack is not empty.

StackEmptyMethodExample.java

import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 66
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}

Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false

Stack Class push() Method

The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to
be pushed into the stack.

Syntax

1. public E push(E item)

Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method

The method removes an object at the top of the stack and returns the same object.
It throws EmptyStackException if the stack is empty.

Syntax
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 67
1. public E pop()

Returns: It returns an object that is at the top of the stack.

Let's implement the stack in a Java program and perform push and pop operations.

StackPushPopExample.java

import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
//pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
//popping elements from the stack
popelmnt(stk);
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 68
{
System.out.println("empty stack");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}

Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 69


stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]

Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we
can store n-number of elements in it as there is no size limit. It is a part of Java
Collection framework since Java 1.2. It is found in the java.util package and
implements the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If


you don't need to use the thread-safe implementation, you should use the ArrayList,
the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent
modification, it fails and throws the ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.

Java Vector class Declaration


1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
Java Vector Constructors

Vector class supports four types of constructors. These are given below:

SN Constructor Description

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 70


1) vector() It constructs an empty vector with the
default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the


specified initial capacity and with its
capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the


capacityIncrement) specified initial capacity and capacity
increment.

4) Vector( Collection<? It constructs a vector that contains the


extends E> c) elements of a collection c.

Java Vector Methods


The following are the list of Vector class methods:

SN Method Description

1) add() It is used to append the specified element in the given


vector.

2) addAll() It is used to append all of the elements in the specified


collection to the end of this Vector.

3) addElement() It is used to append the specified component to the end


of this vector. It increases the vector size by one.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 71


Java Vector Example
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+vec);
}
}

Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Java Vector Example 2


import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 72


vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}

Output:

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 73


Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a String into tokens. It is


simple way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O
chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.

Constructors of the StringTokenizer Class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 74


StringTokenizer(String str, It creates StringTokenizer with specified string
String delim) and delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string,


String delim, boolean delimiter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens.
If it is false, delimiter characters serve to
separate tokens.

Methods of the StringTokenizer Class

The six useful methods of the StringTokenizer class are as follows:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the


StringTokenizer object.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 75


String nextToken(String It returns the next token based on the delimiter.
delim)

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is


Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class

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

Simple.java

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

Output:
my
name
is
khan

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 76


The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().
Example of nextToken(String delim) method of the StringTokenizer class

Test.java

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

Output:
Next token is : my

Java BitSet Class

The Java BitSet class implements a vector of bits. The BitSet grows automatically as
more bits are needed. The BitSet class comes under java.util package. The BitSet
class extends the Object class and provides the implementation of Serializable and
Cloneable interfaces.

Each component of bit set contains at least one Boolean value. The contents of one
BitSet may be changed by other BitSet using logical AND, logical OR and logical
exclusive OR operations. The index of bits of BitSet class is represented by positive
integers.

Each element of bits contains either true or false value. Initially, all bits of a set have
the false value. A BitSet is not safe for multithreaded use without using external
synchronization.

Note: Passing a null parameter to any of the methods of BitSet class will throw a
NullPointerException.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 77


Java Calendar Class

Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.

Java Calendar class declaration


Let's see the declaration of java.util.Calendar class.

public abstract class Calendar extends Object


implements Serializable, Cloneable, Comparable<Calendar>

Java Calendar Class Example


import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}

Output:
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

Java Calendar Class Example: get()


import java.util.*;
public class CalendarExample2{
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 78
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("At present Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("At present Calendar's Day: " + calendar.get(Calendar.DATE));
}
}

Output:
At present Calendar's Year: 2017
At present Calendar's Day: 20

Java Random class

Java Random class is used to generate a stream of pseudorandom numbers. The


algorithms implemented by Random class use a protected utility method than can
supply up to 32 pseudo randomly generated bits on each invocation.

Example 1
import java.util.Random;
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
System.out.println("Longs value : "+random.longs());
// Returns the next pseudorandom boolean value
boolean val = random.nextBoolean();
System.out.println("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
random.nextBytes(bytes);
System.out.print("Random bytes = ( ");
for(int i = 0; i< bytes.length; i++)
{

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 79


System.out.printf("%d ", bytes[i]);
}
System.out.print(")");
}
}

Output:
Longs value : java.util.stream.LongPipeline$Head@14ae5a5
Random boolean value : true
Random bytes = ( 57 77 8 67 -122 -71 -79 -62 53 19 )

Example 2
import java.util.Random;
public class JavaRandomExample2 {
public static void main(String[] args) {
Random random = new Random();
//return the next pseudorandom integer value
System.out.println("Random Integer value : "+random.nextInt());
// setting seed
long seed =20;
random.setSeed(seed);
//value after setting seed
System.out.println("Seed value : "+random.nextInt());
//return the next pseudorandom long value
Long val = random.nextLong();
System.out.println("Random Long value : "+val);
}
}

Output:
Random Integer value : 1294094433
Seed value : -1150867590
Random Long value : -7322354119883315205

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 80


Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to
read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.

The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression. It is the simplest way to get input in Java. By the help of
Scanner in Java, we can get input from the user in primitive types such as int, long,
double, byte, float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.

Java Scanner Class Declaration


public final class Scanner
extends Object
implements Iterator<String>

How to get Java Scanner


To get the instance of Java Scanner which reads input from the user, we need to
pass the input stream (System.in) in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner(System.in);

To get the instance of Java Scanner which parses the strings, we need to pass the
strings in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 81


Java Scanner Class Constructors
SN Constructor Description

1) Scanner(File source) It constructs a new Scanner that


produces values scanned from
the specified file.

2) Scanner(File source, String It constructs a new Scanner that


charsetName) produces values scanned from
the specified file.

3) Scanner(InputStream source) It constructs a new Scanner that


produces values scanned from
the specified input stream.

4) Scanner(InputStream source, String It constructs a new Scanner that


charsetName) produces values scanned from
the specified input stream.

5) Scanner(Readable source) It constructs a new Scanner that


produces values scanned from
the specified source.

6) Scanner(String source) It constructs a new Scanner that


produces values scanned from
the specified string.

7) Scanner(ReadableByteChannel It constructs a new Scanner that


source) produces values scanned from

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 82


the specified channel.

8) Scanner(ReadableByteChannel source, It constructs a new Scanner that


String charsetName) produces values scanned from
the specified channel.

9) Scanner(Path source) It constructs a new Scanner that


produces values scanned from
the specified file.

10) Scanner(Path source, String It constructs a new Scanner that


charsetName) produces values scanned from
the specified file.

Example 1

Let's see a simple example of Java Scanner where we are getting a single input from
the user. Here, we are asking for a string through in.nextLine() method.

import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

Output:
Enter your name: sonoo jaiswal

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 83


Name is: sonoo jaiswal

Example 2
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details -------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}

Output:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 84


Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

Example 3
import java.util.*;
public class ScannerClassExample2 {
public static void main(String args[]){
String str = "Hello/This is JavaTpoint/My name is Abhishek.";
//Create scanner with the specified String Object
Scanner scanner = new Scanner(str);
System.out.println("Boolean Result: "+scanner.hasNextBoolean());
//Change the delimiter of this scanner
scanner.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(scanner.hasNext()){
System.out.println(scanner.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +scanner.delimiter());
scanner.close();
}
}

Output:
Boolean Result: false
---Tokenizes String---
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 85


Java Date and Time
The java.time, java.util, java.sql and java.text packages contains classes for
representing date and time. Following classes are important for dealing with date in
Java.

Java Date and Time APIs


Java provide the date and time functionality with the help of two packages java.time
and java.util. The package java.time is introduced in Java 8, and the newly introduced
classes tries to overcome the shortcomings of the legacy java.util.Date and
java.util.Calendar classes.

Classical Date Time API Classes

The primary classes before Java 8 release were:

Java.lang.System: The class provides the currentTimeMillis() method that returns


the current time in milliseconds. It shows the current date and time in milliseconds
from January 1st 1970.

java.util.Date: It is used to show specific instant of time, with unit of millisecond.

java.util.Calendar: It is an abstract class that provides methods for converting


between instances and manipulating the calendar fields in different ways.

java.text.SimpleDateFormat: It is a class that is used to format and parse the dates


in a predefined manner or user defined pattern.

java.util.TimeZone: It represents a time zone offset, and also figures out daylight
savings.

Drawbacks of existing Date/Time API's

1. Thread safety: The existing classes such as Date and Calendar does not
provide thread safety. Hence it leads to hard-to-debug concurrency issues that
are needed to be taken care by developers. The new Date and Time APIs of
Java 8 provide thread safety and are immutable, hence avoiding the
concurrency issue from developers.
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 86
2. Bad API designing: The classic Date and Calendar APIs does not provide
methods to perform basic day-to-day functionalities. The Date and Time
classes introduced in Java 8 are ISO-centric and provides number of different
methods for performing operations regarding date, time, duration and periods.
3. Difficult time zone handling: To handle the time-zone using classic Date and
Calendar classes is difficult because the developers were supposed to write the
logic for it. With the new APIs, the time-zone handling can be easily done with
Local and ZonedDate/Time APIs.
New Date Time API in Java 8

The new date API helps to overcome the drawbacks mentioned above with the
legacy classes. It includes the following classes:

java.time.LocalDate: It represents a year-month-day in the ISO calendar and is


useful for representing a date without a time. It can be used to represent a date only
information such as a birth date or wedding date.

java.time.LocalTime: It deals in time only. It is useful for representing human-based


time of day, such as movie times, or the opening and closing times of the local
library.

java.time.LocalDateTime: It handles both date and time, without a time zone. It is a


combination of LocalDate with LocalTime.

java.time.ZonedDateTime: It combines the LocalDateTime class with the zone


information given in ZoneId class. It represent a complete date time stamp along
with timezone information.

java.time.OffsetTime: It handles time with a corresponding time zone offset from


Greenwich/UTC, without a time zone ID.

java.time.OffsetDateTime: It handles a date and time with a corresponding time


zone offset from Greenwich/UTC, without a time zone ID.

java.time.Clock : It provides access to the current instant, date and time in any
given time-zone. Although the use of the Clock class is optional, this feature allows

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 87


us to test your code for other time zones, or by using a fixed clock, where time does
not change.

java.time.Instant : It represents the start of a nanosecond on the timeline (since


EPOCH) and useful for generating a timestamp to represent machine time. An
instant that occurs before the epoch has a negative value, and an instant that occurs
after the epoch has a positive value.

java.time.Duration : Difference between two instants and measured in seconds or


nanoseconds and does not use date-based constructs such as years, months, and
days, though the class provides methods that convert to days, hours, and minutes.

java.time.Period : It is used to define the difference between dates in date-based


values (years, months, days).

java.time.ZoneId : It states a time zone identifier and provides rules for converting
between an Instant and a LocalDateTime.

java.time.ZoneOffset : It describe a time zone offset from Greenwich/UTC time.

java.time.format.DateTimeFormatter : It comes up with various predefined


formatter, or we can define our own. It has parse() or format() method for parsing
and formatting the date time values.

B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 88


UNIT-5 JAVA PROGRAMMING
Applet:

Applet is a special type of program that is embedded in the webpage to generate


the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class


provides 1 life cycle methods for an applet.
java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create
an html file and place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java. Now
Html file is not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java
Applet Architecture
When you write a Java application for time series data, you use the JDBC Driver to connect to
the database, as shown in the following figure.

Figure 1. Runtime architecture for Java programs that connect to a database

The Java application makes calls to the JDBC driver, which sends queries and other SQL statements to
the database. The database sends query results to the JDBC driver, which sends them on to the Java
application.
You can also use the time series Java classes in Java applets and servlets, as shown in the following
figures.

Figure 2. Runtime architecture for a Java applet

The database server is connected to the JDBC driver, which is connected to the applet. The applet is
also connected to a browser, which is connected to a web server that communicates with the database.

Figure 3. Runtime architecture for a Java servlet


A request from an application goes through a web server, an HTTP servlet subclass, and the JDBC
driver to the database. The database sends responses back along the same path.

An Applet Skeleton

Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized. This

method is called only once during the runtime of applet.

 start() : start() method is called after init(). This method is called to restart an applet after

it has been stopped.

 stop() : stop() method is called to suspend thread that does not need to run when applet

is not visible.

 destroy() : destroy() method is called when your applet needs to be removed completely

from memory.

Example of an Applet Skeleton

import java.awt.*;

import java.applet.*;

public class AppletTest extends Applet

public void init()

//initialization

}
public void start ()

//start or resume execution

public void stop()

//suspend execution

public void destroy()

//perform shutdown activity

public void paint (Graphics g)

//display the content of window

Example of an Applet

import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet

int height, width;

public void init()

height = getSize().height;
width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(10, 30, 120, 120, 2, 3);

Running Applet using Applet Viewer

To execute an Applet with an applet viewer, write short HTML file as discussed above. If name it
as run.htm, then the following command will run your applet program.

f:/>appletviewer run.htm
Requesting Repainting
As a general rule, an applet writes to its window only when its paint( ) method is called by the
AWT. This raises an interesting question: How can the applet itself cause its window to be
updated when its information changes? For example, if an applet is displaying a moving banner,
what mechanism does the applet use to update the window each time this banner scrolls?
Remember, one of the fundamental architectural constraints imposed on an applet is that it must
quickly return control to the run-time system. It cannot create a loop inside paint( ) that
repeatedly scrolls the banner, for example. This would prevent control from passing back to the
AWT. Given this constraint, it may seem that output to your applet’s window will be difficult at
best. Fortunately, this is not the case. Whenever your applet needs to update the information
displayed in its window, it simply calls repaint( ).

The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a
call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus,
for another part of your applet to output to its window, simply store the output and then
call repaint( ). The AWT will then execute a call to paint( ), which can display the stored
information. For example, if part of your applet needs to output a string, it can store this string in
a String variable and then call repaint( ). Inside paint( ), you will output the string
using drawString( ).

The repaint( ) method has four forms. Let’s look at each one, in turn. The simplest version
of repaint( ) is shown here:

void repaint( )

This version causes the entire window to be repainted. The following version specifies a region
that will be repainted:

void repaint(int left, int top, int width, int height)

Here, the coordinates of the upper-left corner of the region are specified by left and top, and the
width and height of the region are passed in width and height. These dimensions are specified in
pixels. You save time by specifying a region to repaint. Window updates are costly in terms of
time. If you need to update only a small portion of the window, it is more efficient to repaint only
that region.

Calling repaint( ) is essentially a request that your applet be repainted sometime soon. However,
if your system is slow or busy, update( ) might not be called immediately. Multiple requests for
repainting that occur within a short time can be collapsed by the AWT in a manner such
that update( ) is only called sporadically. This can be a problem in many situations, including
animation, in which a consistent update time is necessary. One solution to this problem is to use
the following forms of repaint( ):

void repaint(long maxDelay)

void repaint(long maxDelay, int x, int y, int width, int height)

Here, maxDelay specifies the maximum number of milliseconds that can elapse before update(
) is called. Beware, though. If the time elapses before update( ) can be called, it isn’t called.
There’s no return value or exception thrown, so you must be careful.
How can output a message on status window.
An applet can output a message to the status window of the browser or applet viewer on which it is running. For
this, it makes a call to showStatus( ) with the string that we want to be displayed. The status window is a place
where the user can give feedback about what is occurring in the applet, suggest options, or report some types of
errors. The status window also makes an excellent debugging aid, because it gives an easy way to
output information about the applet. The applet below shows the use of showStatus( ):

import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50> </applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.pink);
}
public void paint (Graphics g)
{
g.drawString("You are in main applet window.", 10, 20);
showStatus("This is the status window.");
}
}

The output of the above Applet code is as follows:


PASSING PARAMETERS TO APPLETS
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:

public String getParameter(String parameterName)


Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Accessing Databases with JDBC:

JDBC Driver

JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

3. Network Protocol driver (fully java driver)

4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of thin driver.

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:

o No client side library is required because of application server that can


perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.

Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage: Drivers depend on the Database.


Architecture of JDBC
The following figure shows the JDBC architecture:

Description of the Architecture:


1. Application: Application in JDBC is a Java applet or a Servlet that communicates with a
data source.
2. JDBC API: JDBC API provides classes, methods, and interfaces that allow Java
programs to execute SQL statements and retrieve results from the database. Some
important classes and interfaces defined in JDBC API are as follows:
 DriverManager
 Driver
 Connection
 Statement
 PreparedStatement
 CallableStatement
 ResultSet
 SQL data

3. Driver Manager: The Driver Manager plays an important role in the JDBC architecture.
The Driver manager uses some database-specific drivers that effectively connect
enterprise applications to databases.
4. JDBC drivers: JDBC drivers help us to communicate with a data source through JDBC.
We need a JDBC driver that can intelligently interact with the respective data source.
Types of JDBC Architecture

There are two types of processing models in JDBC architecture: two-tier and three-tier.
These models help us to access a database. They are:

1. Two-tier model

In this model, a Java application directly communicates with the data source. JDBC
driver provides communication between the application and the data source. When a
user sends a query to the data source, the answers to those queries are given to the user
in the form of results.

We can locate the data source on a different machine on a network to which a user is
connected. This is called a client/server configuration, in which the user machine acts as
a client, and the machine with the data source acts as a server.

2. Three-tier model

In the three-tier model, the query of the user queries goes to the middle-tier services.
From the middle-tier service, the commands again reach the data source. The results of
the query go back to the middle tier.

From there, it finally goes to the user. This type of model is beneficial for management
information system directors.

Major Classes and Interfaces used to developing Java Application.


Some of major classes and interfaces which are frequently used while developing a Java application are as
follows:
• DriverManager class
• Driver interface
• Connection interface
• Statement interface
DriverManagerClass

It is a predefined class present/declared in java.sql package. It is a non-abstract class in the JDBC API. It has no
constructor which implies that this class cannot be inherited or initialized directly.
All the methods or properties of this class are declared as static, so it is not necessary to construct an object of
DriverManager Class. We can call these static methods using class name.
The main responsibility of the DriverManager class is preparing a connection by using Driver implementation
that accepts the given JDBC URL.
Methods in DriverManager
(a) public static Connection getConnection (String url, String user name, String pswd);
Establishes connection between driver and database. This class selects a driver from the list of drivers and creates
a connection by checking user parameter for which the connection is being made. Password parameter represents
the password of the user.
(b) public static Driver getDriver (String url) throws SQLException
Locates the requested driver in the DriverManager class. The URL parameter specifies the URL of requested
driver.
(c) public static void register (Driver drvr) throws SQLException:
Registers a requested driver with DriverManager Class.
(d) public static void deregister (Driver drvr) throws SQLException
Drops a driver from the list of the driver maintained by DriverManager.
Driver Interface

It is a predefined interface present in java.sql. package. It is a basic interface that every JDBC driver provider has
to implement. The java.sql.Driver is an Interface defined under JDBCAPI to describe an object that is responsible
to establish connection to database. All the driver classes implement this interface to connect to a database.
Methods in Driver Interface
(a) public Connection connect (String url, Properties info)
This method establishes connectivity with database. The URL parameter specifies a URL that describes the
database details to which the driver is to be connected. The info parameter specifies the information of the
tag/value pair used in driver.
Connection Interface

It is an interface present in java.sql package. This interface defines an abstraction to access the session,
established with the database server. The JDBC connection helps to perform the following operation:
• Create JDBC Statement
• Control local transaction
Methods in Connection Interface
(a) public void close () throws SQLException
Closes the connection and releases the connection object associated with the connected database.
(b) public Statement createStatement () throws SQLException
Create a Statement object to send sql statements to the specified database.
(c) public PreparedStatement prepareStatement (String sql) throws SQLException
Create a PreparedStatement object to send sql statements over a connection.
(d) public CallableStatement prepareCall (String sql) throws SQLException
Create a CallableStatement object for calling database stored procedures.
(e) public void commit () throws SQLException
Commits the changes made in the previous commit and releases any database locks held by the current
Connection object.
(f) public void rollback () throws SQLException
Rolls back all the transactions and releases any locks that are currently held by the Connection object.
Statement Interface

It is a predefined interface present in java.sql package. It is a part of JDBC API that abstracts an object. It is
responsible to execute sql statement and return the result. A
Statement object can open a single ResultSet object at a time.
The PreparedStatement interface is dealing with IN parameter whereas the CallableStatement interface deals with
both IN and OUT.
Methods of Statement Interface
(a) public int executeUpdate (String sql) throws SQLException
Execute the Insert, Update and Delete Statement or the SQL DDL statements.
(b) public ResultSet executeQuery (String sql) throws SQLException
Execute a sql command and return a single ResultSet.
(c) public void close () throws SQLException
Closes the Statement object, therefore, it releases its control from the database and also from the connection.
(d) public ResultSet getResultSet () throws SQLException
Retrieves the current Resultset object generated by Statement object.
(e) public Connection getConnection () throws SQLException
Accepts the Connection object made to the database.
ResultSet Interface

This interface provides methods for the retrieval of data returned by an SQL statement execution. A ResultSet
maintains a cursor pointing to its current row of data. The most often used methods, namely, getXXX and
updateXXX methods are present in this interface.
Methods in ResultSet
(a) public booleannext () throws SQLException
Moves the cursor down one row from its current position.
(b) public void close () throws SQLException
Releases this ResultSet object’s database and JDBC resources immediately instead of waiting for this to happen
when it is automatically closed.
(c) public booleanwasNull () throws SQLException
Reports whether the last column read had a value of SQL NULL.
(d) public StringgetXXX (int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as per the type of data.
(e) public void beforeFirst () throws SQLException
Moves the cursor to the front of this ResultSet object, just before the first row.
(f) public void afterLast () throws SQLException
Moves the cursor to the end of this ResultSet object, just after the last row.
(g) public booleanabsolute (int row) throws SQLException
Moves the cursor to the given row number in this ResultSet object.
(h) public booleanprevious () throws SQLException
Moves the cursor to the previous row in this ResultSet object.
(i) public void deleteRow () throws SQLException
Deletes the current row from this ResultSet object and from the underlying database.
(j) public void insertRow () throws SQLException
Inserts the contents of the insert row into this ResultSet object and into the database.

Steps to Design JDBC Applications in Java


In this article, I am going to discuss Steps to Design JDBC Applications in Java with Examples.
Please read our previous article where we discussed JDBC Drivers in Java Applications. At the
end of this article, you will understand the following pointers in detail.
1. Steps to Design JDBC Applications in Java
2. Establishing Connection
3. Creating Statement Object
4. Submitting SQL Statement
5. Database Connectivity with Oracle
6. Connection Interface in JDBC
7. Statement Interface in JDBC
Steps to Design JDBC Applications in Java:
Let us understand how to perform CRUD operations in Java Applications using JDBC step by
step. The following diagram shows the different steps required to develop a JDBC application in
Java.
Establishing Connection:
In the JDBC programming model, the first step is to establish the connection between the java
application and the database server. Establishing the database connection in a java program
involves two steps
Step1. Loading JDBC driver from secondary memory into primary memory.
First, you need to load the driver or register it before using it in the program. Registration is to be
done once in your program. In java.lang.Class class, there is a static method “forName”. This
method is used to load the JDBC driver into the application process space.
Syntax: public static void forName(String className) throws ClassNotFoundException
You can register the Driver by following two ways :
1. Class.forName(“driver class name”) : Here we load the driver’s class file into memory at
the runtime. No need of using new or creation of objects.
2. DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static
member register. Here we call the constructor of the driver class at compile time.
When the forName() method is successfully executed, three things happen in the background
1. The driver class is loaded into memory.
2. The driver class object is created.
3. The driver class is registered with DriverManager.
Step2.Requesting for database connection
In order to establish a communication with the database, you must first open a JDBC connection
to the database. After loading the driver, establish a connection. In java.sql.DriverManager class
there is a static method “getConnection”. This method is used by the java program to request the
database connection. Following are three methods of DriverManager.getConnection() :
1. getConnection(String url)
2. getConnection(String url, Properties prop)
3. getConnection(String url, String user, String password)
Syntax :
public static Connection getConnection(String url,String name,String password) throws SQ
LException
Example:
Connection con = DriverManager.getConnection(“connection string”, “user name”,
“password”);
Once the above statement is executed, the client connects to the database server. Object-oriented
representation of JDBC client’s session with the database server is nothing
but java.sql.Connection object.
Note: Internally getConnection() method call connect method of connection class.
Creating Statement Object:
Once a connection is established you can interact with the database.
The createStatement() method of the Connection interface is used to create a statement. The
object of the statement is responsible to execute queries with the database.
Syntax : public Statement createStatement()throws SQLException
Example: Statement st = con.createStatement();
The Statement object is designed to submit SQL statements from the JDBC client to the DBMS
(via JDBC driver).
Submitting the SQL Statement:
Now its time to process the result by executing the query. The java.sql.Statement object has two
important methods to submit SQL statements to the DBMS
1. executeUpdate(String dml):– The executeUpdate(SQL query) method of Statement
interface is used to execute queries of updating/inserting. This method is used to submit
DML (INSERT, UPDATE, and DELETE) SQL statements.
2. executeQuery (String drl):– The executeQuery() method of the Statement interface is used
to execute queries to the database. This method returns the object of ResultSet that can be
used to get all the records of a table. This method is used to submit the SELECT statement.
Syntax : public ResultSet executeQuery(String sql) throws SQLException
Close the Connection
So finally we have sent the data to the specified location. By closing the connection object
statement and ResultSet will be closed automatically. The close() method of the Connection
interface is used to close the connection.
Syntax : public void close()throws SQLException
Let us understand the above-discussed steps with an example. We are going to interact with
Oracle Database.
Database Connectivity with Oracle
To connect the java application with the oracle database, we need to know the following
information for the oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where JDBC is the API, Oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also use
the IP address, 1521 is the port number and XE is the Oracle service name. You may get all
this information from the tnsnames.ora file.
3. Username: The default username for the oracle database is the system.
4. Password: It is the password given by the user at the time of installing the oracle database.
Create a Table
Before establishing a connection, first, we need to create a table in the oracle database. Please
execute the below SQL query to create a table:
CREATE TABLE ACCOUNT (accnonumber(8) primary key, name varchar2(12), balance
number(8,2));
Sample Program to connect with Oracle database

Code Explanation:
Line1: By importing the java.sql package, JDBC API is made available to the JDBC application.
Line2: A user-defined class “AccountStoringApplication” is defined here.
1. This JDBC application is a standalone application.
2. Every standalone application should have a main method in java.
3. To encapsulate the main method, the class “AccountStoringApplication ” is defined here.
Line 4 & 5: the main method is defined as is standalone JDBC application.
Within the main method body during the forName() method call there is a chance
of java.lang.ClassNotFoundException raising. During other JDBC API calls, there is a chance
of java.sql.SQLException getting raised. These are checked exceptions. These checked
exceptions must be handled. Non-handling of checked exceptions in a java application is a
syntactical error.
To pass (temporarily handled) on the exception handling duty to the higher level and at the same
to overcome the compilation error, a throws clause is written for the main method.
Line6:
The main method is calling forName() method on the Class(name of the class) class by specifying
oracle corporation developed TYPE- 4 driver class as an argument. The forName() method loads
the oracle driver class from secondary memory into primary memory.
In OracleDriver class (in fact in every driver class) there is a static block. In that block, two things
are performed
1. Driver class object creation.
2. Registering it with DriverManager
Static
{
OracleDriver d = new OracleDriver();
DriverManager.registerDriver(d);
}
If the specified driver class is not found at the specified location, the forName() method causes
ClassNotFoundException. In the case of OracleDriver, we need to place any one of the following
jar files into the classpath.
1. classes12.jar
2. ojdbc14.jar
3. jdbc5.jar
4. ojdbc.jar
For example: set CLASSPATH = .;\ojdbc14.jar
Here dot (.) represent the current directory.
Line7:
The main method is calling the getConnection() method on DriverManager class by supplying the
connection string as the first argument, username as the second, and password as the third
argument. (Username and password are the database user name and password).
The connection string is “jdbc:oracle:thin:@localhost:1521:xe”
Here,
1. jdbc = main protocol
2. oracle = sub protocol
3. thin = type of driver (here type 4)
4. localhost = IP address of the current machine
5. 1521 = port number
6. xe = database service name.
Note: port number and database service name we have to check in the “tnsnames.ora” file
Line 8 & 9:
Creating a Statement object and executing the SQL statement against the Oracle database.
Line 13 & 14:
Closing the statement and connection object.
Note: For the insert, update, and delete operations, the DBMS returns an integer number. In the
case of INSERT if the record is successfully inserted into the database then DBMS returns 1. In
the case of UPDATE if the record is successfully updated then it returns the no i.e. updated
number of records. And in the case of DELETE, it returns 1 if the successful record is deleted else
it returns 0.
Connection Interface in JDBC
The java.sql.Connection interface represents a session between a java application and a database.
All SQL statements are executed and results are returned within the context of a Connection
Object. The connection interface is mainly used to create java.sql.statement,
java.sql.PreparedStatement and java.sql.CallableStatement objects.
For example :
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“dbc:odbc:DSN”);
Methods of Connection Interface
1. public Statement CreateStatement(): creates a statement object that can be used to
execute SQL queries.
2. public Statement createStatement(int resultSetType, int
resultSetConcurrency): creates a statement object that will generate ResultSet objects
with the given type and concurrency.
3. public void setAutoCommit(boolean status): is used to set the commit status. By default
it is true.
4. public void comit(): saves the changes made since the previous commit/rollback
permanent.
5. public void rollback(): Drops all changes made since the previous commit/rollback.
6. public void close(): closes the connection and releases JDBC resources immediately.
Statement Interface in JDBC
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreperedStatement interface define the methods and properties that enable
you to send SQL or PL/SQL commands and receive data from your database. They also define
methods that help bridge data type differences between Java and SQL data types used in a
database.
Methods of Statement Interface
1. public ResultSet executeQuery(String sql): is used to execute the SELECT query. It
returns the object of ResultSet.
2. public int executeUpdate(String sql): is used to execute the specified query, it may be
created, drop, insert, update, delete, etc.
3. public Boolean execute(String sql): is used to execute queries that may return multiple
results.
4. public int[] executeBatch() : is used to execute batch of commands.
JDBC - Create Database Example
Before executing the following example, make sure you have the following in place
 You should have admin privilege to create a database in the given schema. To execute the
following example, you need to replace the username and password with your actual user name
and password.
 Your MySQL or whatever database is up and running.

Required Steps
The following steps are required to create a new Database using JDBC application
 Import the packages − Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create
a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database
URL as mentioned in the below example.
 Execute a query − Requires using an object of type Statement for building and submitting
an SQL statement to the database.
 Clean up the environment . try with resources automatically closes the resources.

Sample Code
Copy and paste the following example in JDBCExample.java, compile and run as
follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>

How to create a table in a database using JDBC API?


You can create a table in a database using the CREATE TABLE query.
Syntax
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
To create a table in a database using JDBC API you need to:

 Register the driver: Register the driver class using the registerDriver() method of
the DriverManager class. Pass the driver class name to it, as parameter.
 Establish a connection: Connect ot the database using the getConnection() method of
the DriverManager class. Passing URL (String), username (String), password (String) as
parameters to it.
 Create Statement: Create a Statement object using the createStatement() method of
the Connection interface.
 Execute the Query: Execute the query using the execute() method of the Statement interface.
Example
Following JDBC program establishes connection with MySQL and creates a table named customers in
the database named SampleDB:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/SampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established. .... ");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to create a table
String query = "CREATE TABLE CUSTOMERS("
+ "ID INT NOT NULL, "
+ "NAME VARCHAR (20) NOT NULL, "
+ "AGE INT NOT NULL, "
+ "SALARY DECIMAL (18, 2), "
+ "ADDRESS CHAR (25) , "
+ "PRIMARY KEY (ID))";
stmt.execute(query);
System.out.println("Table Created ..... ");
}
}

Output
Connection established......
Table Created......
The show tables command gives you the list of tables in the current database in
MySQL.
If you verify the list of tables in the database named sampledb, you can observe
the newly created table in it as:
mysql> show tables;
+ +
| Tables_in_sampledb |
+ +
| articles |
| customers |
| dispatches |
| technologies |
| tutorial |
+ +
5 rows in set (0.00 sec)

You might also like