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

OOPs (Object-Oriented Programming System)

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

OOPs (Object-Oriented Programming System)

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

OOPs (Object-Oriented Programming System)

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:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:

• Coupling
• Cohesion
• Association
• Aggregation
• Composition
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.

Naming Conventions of the Different Identifiers


The following table shows the popular conventions used for the different identifiers.

Identifie Naming Rules Examples


rs Type

Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, System, {
Thread, etc. //code snippet
Use appropriate words, instead of acronyms. }

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as Runnable, Remote, {
ActionListener. //code snippet
Use appropriate words, instead of acronyms. }

Method It should start with lowercase letter. class Employee


It should be a verb such as main(), print(), println(). {
If the name contains multiple words, start it with a // method
lowercase letter followed by an uppercase letter void draw()
such as actionPerformed(). {
//code snippet
}
}

Variable It should start with a lowercase letter such as id, class Employee
name. {
It should not start with the special characters like & // variable
(ampersand), $ (dollar), _ (underscore). int id;
If the name contains multiple words, start it with //code snippet
the lowercase letter followed by an uppercase }
letter such as firstName, lastName.
Avoid using one-character variables such as x, y, z.

Package It should be a lowercase letter such as java, lang. //package


If the name contains multiple words, it should be package
separated by dots (.) such as java.util, java.lang. com.javatpoint;
class Employee
{
//code snippet
}

Constant It should be in uppercase letters such as RED, class Employee


YELLOW. {
If the name contains multiple words, it should be //constant
separated by an underscore(_) such as static final int
MAX_PRIORITY. MIN_AGE = 18;
It may contain digits but not as the first letter. //code snippet
}

Objects and Classes in Java


• Object in Java
• Class in Java
• Instance Variable in Java
• Method in Java
• Example of Object and class that maintains the records of student
• Anonymous Object

In this page, we will learn about Java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only.

What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.

An object has three characteristics:

Backward Skip 10sPlay VideoForward Skip 10s


• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

• An object is a real-world entity.


• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

Instance variable in Java


A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.
ADVERTISEMENT
ADVERTISEMENT

Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method

• Code Reusability
• Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.

Here, we are creating a main() method inside the class.


File: Student.java

5. //Java Program to illustrate how to define a class and fields


6. //Defining a Student class.
7. class Student{
8. //defining fields
9. int id;//field or data member or instance variable
10. String name;
11. //creating main method inside the Student class
12. public static void main(String args[]){
13. //Creating an object or instance
14. Student s1=new Student();//creating an object of Student
15. //Printing values of the object
16. System.out.println(s1.id);//accessing member through reference variable
17. System.out.println(s1.name);
18. }
19. }

3 Ways to initialize object


There are 3 ways to initialize object in Java.

20. By reference variable


21. By method
22. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
ADVERTISEMENT
ADVERTISEMENT

File: TestStudent2.java

23. class Student{


24. int id;
25. String name;
26. }
27. class TestStudent2{
28. public static void main(String args[]){
29. Student s1=new Student();
30. s1.id=101;
31. s1.name="Sonoo";
32. System.out.println(s1.id+" "+s1.name);//printing members with a white space
33. }
34. }
Test it Now

Output:

101 Sonoo

We can also create multiple objects and store information in it through reference variable.

File: TestStudent3.java

35. class Student{


36. int id;
37. String name;
38. }
39. class TestStudent3{
40. public static void main(String args[]){
41. //Creating objects
42. Student s1=new Student();
43. Student s2=new Student();
44. //Initializing objects
45. s1.id=101;
46. s1.name="Sonoo";
47. s2.id=102;
48. s2.name="Amit";
49. //Printing data
50. System.out.println(s1.id+" "+s1.name);
51. System.out.println(s2.id+" "+s2.name);
52. }
53. }
Test it Now

Output:

101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method


In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data)
of the objects by invoking the displayInformation() method.

File: TestStudent4.java

54. class Student{


55. int rollno;
56. String name;
57. void insertRecord(int r, String n){
58. rollno=r;
59. name=n;
60. }
61. void displayInformation(){System.out.println(rollno+" "+name);}
62. }
63. class TestStudent4{
64. public static void main(String args[]){
65. Student s1=new Student();
66. Student s2=new Student();
67. s1.insertRecord(111,"Karan");
68. s2.insertRecord(222,"Aryan");
69. s1.displayInformation();
70. s2.displayInformation();
71. }
72. }
Test it Now

Output:

111 Karan
222 Aryan

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

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

73. class Employee{


74. int id;
75. String name;
76. float salary;
77. void insert(int i, String n, float s) {
78. id=i;
79. name=n;
80. salary=s;
81. }
82. void display(){System.out.println(id+" "+name+" "+salary);}
83. }
84. public class TestEmployee {
85. public static void main(String[] args) {
86. Employee e1=new Employee();
87. Employee e2=new Employee();
88. Employee e3=new Employee();
89. e1.insert(101,"ajeet",45000);
90. e2.insert(102,"irfan",25000);
91. e3.insert(103,"nakul",55000);
92. e1.display();
93. e2.display();
94. e3.display();
95. }
96. }
Test it Now

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

97. class Rectangle{


98. int length;
99. int width;
100. void insert(int l, int w){
101. length=l;
102. width=w;
103. }
104. void calculateArea(){System.out.println(length*width);}
105. }
106. class TestRectangle1{
107. public static void main(String args[]){
108. Rectangle r1=new Rectangle();
109. Rectangle r2=new Rectangle();
110. r1.insert(11,5);
111. r2.insert(3,15);
112. r1.calculateArea();
113. r2.calculateArea();
114. }
115. }
Test it Now

Output:

55
45

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


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

• By new keyword
• By newInstance() method
• By clone() method
• By deserialization
• By factory method etc.

We will learn these ways to create object later.


Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only.

If you have to use an object only once, an anonymous object is a good approach. For example:

116. new Calculation();//anonymous object

Calling method through a reference:

117. Calculation c=new Calculation();


118. c.fact(5);

Calling method through an anonymous object

119. new Calculation().fact(5);


Let's see the full example of an anonymous object in Java.

120. class Calculation{


121. void fact(int n){
122. int fact=1;
123. for(int i=1;i<=n;i++){
124. fact=fact*i;
125. }
126. System.out.println("factorial is "+fact);
127. }
128. public static void main(String args[]){
129. new Calculation().fact(5);//calling method with anonymous object
130. }
131. }

Output:

Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

132. int a=10, b=20;

Initialization of refernce variables:

133. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see the example:

134. //Java Program to illustrate the use of Rectangle class which


135. //has length and width data members
136. class Rectangle{
137. int length;
138. int width;
139. void insert(int l,int w){
140. length=l;
141. width=w;
142. }
143. void calculateArea(){System.out.println(length*width);}
144. }
145. class TestRectangle2{
146. public static void main(String args[]){
147. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
148. r1.insert(11,5);
149. r2.insert(3,15);
150. r1.calculateArea();
151. r2.calculateArea();
152. }
153. }
Test it Now

Output:

55
45

Real World Example: Account


File: TestAccount.java

154. //Java Program to demonstrate the working of a banking-system


155. //where we deposit and withdraw amount from our account.
156. //Creating an Account class which has deposit() and withdraw() methods
157. class Account{
158. int acc_no;
159. String name;
160. float amount;
161. //Method to initialize object
162. void insert(int a,String n,float amt){
163. acc_no=a;
164. name=n;
165. amount=amt;
166. }
167. //deposit method
168. void deposit(float amt){
169. amount=amount+amt;
170. System.out.println(amt+" deposited");
171. }
172. //withdraw method
173. void withdraw(float amt){
174. if(amount<amt){
175. System.out.println("Insufficient Balance");
176. }else{
177. amount=amount-amt;
178. System.out.println(amt+" withdrawn");
179. }
180. }
181. //method to check the balance of the account
182. void checkBalance(){System.out.println("Balance is: "+amount);}
183. //method to display the values of an object
184. void display(){System.out.println(acc_no+" "+name+" "+amount);}
185. }
186. //Creating a test class to deposit and withdraw amount
187. class TestAccount{
188. public static void main(String[] args){
189. Account a1=new Account();
190. a1.insert(832345,"Ankit",1000);
191. a1.display();
192. a1.checkBalance();
193. a1.deposit(40000);
194. a1.checkBalance();
195. a1.withdraw(15000);
196. a1.checkBalance();
197. }}
Test it Now

Output:

832345 Ankit 1000.0


Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

Constructors in Java
• Types of constructors
o Default Constructor
o Parameterized Constructor
• Constructor Overloading
• Does constructor return any value?
• Copying the values of one object into another
• Does constructor perform other tasks instead of the initialization

In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

Note: It is called constructor because it constructs the values at the time of object creation.
It is not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
Rules for creating Java constructor

There are two rules defined for the constructor.

198. Constructor name must be the same as its class name


199. A Constructor must have no explicit return type
200. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other
words, we can have private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

201. Default constructor (no-arg constructor)


202. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.

Example of Constructor Overloading

203. //Java program to overload constructors


204. class Student5{
205. int id;
206. String name;
207. int age;
208. //creating two arg constructor
209. Student5(int i,String n){
210. id = i;
211. name = n;
212. }
213. //creating three arg constructor
214. Student5(int i,String n,int a){
215. id = i;
216. name = n;
217. age=a;
218. }
219. void display(){System.out.println(id+" "+name+" "+age);}
220.
221. public static void main(String args[]){
222. Student5 s1 = new Student5(111,"Karan");
223. Student5 s2 = new Student5(222,"Aryan",25);
224. s1.display();
225. s2.display();
226. }
227. }

Difference between constructor and method in Java


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

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class The method name may or may not
name. be same as the class name.

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
ADVERTISEMENT
ADVERTISEMENT

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

• By constructor
• By assigning the values of one object into another
• By clone() method of Object class

In this example, we are going to copy the values of one object into another using Java
constructor.

228. //Java program to initialize the values from one object to another object.
229. class Student6{
230. int id;
231. String name;
232. //constructor to initialize integer and string
233. Student6(int i,String n){
234. id = i;
235. name = n;
236. }
237. //constructor to initialize another object
238. Student6(Student6 s){
239. id = s.id;
240. name =s.name;
241. }
242. void display(){System.out.println(id+" "+name);}
243.
244. public static void main(String args[]){
245. Student6 s1 = new Student6(111,"Karan");
246. Student6 s2 = new Student6(s1);
247. s1.display();
248. s2.display();
249. }
250. }
Test it Now

Output:

111 Karan
111 Karan

ADVERTISEMENT

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.

251. class Student7{


252. int id;
253. String name;
254. Student7(int i,String n){
255. id = i;
256. name = n;
257. }
258. Student7(){}
259. void display(){System.out.println(id+" "+name);}
260.
261. public static void main(String args[]){
262. Student7 s1 = new Student7(111,"Karan");
263. Student7 s2 = new Student7();
264. s2.id=s1.id;
265. s2.name=s1.name;
266. s1.display();
267. s2.display();
268. }
269. }
Test it Now

Output:

111 Karan
111 Karan

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


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

Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the java.lang.reflect package.

static keyword
• Static variable
• Program of the counter without static variable
• Program of the counter with static variable
• Static method
• Restrictions for the static method
• Why is the main method static?
• Static block
• Can we execute a program without main method?

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

The static can be:

270. Variable (also known as a class variable)


271. Method (also known as a class method)
272. Block
273. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.
ADVERTISEMENT
ADVERTISEMENT

• The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
• The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

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

) Java static method


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

• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.

Example of static method

274. //Java Program to demonstrate the use of a static method.


275. class Student{
276. int rollno;
277. String name;
278. static String college = "ITS";
279. //static method to change the value of static variable
280. static void change(){
281. college = "BBDIT";
282. }
283. //constructor to initialize the variable
284. Student(int r, String n){
285. rollno = r;
286. name = n;
287. }
288. //method to display values
289. void display(){System.out.println(rollno+" "+name+" "+college);}
290. }
291. //Test class to create and display the values of object
292. public class TestStaticMethod{
293. public static void main(String args[]){
294. Student.change();//calling change method
295. //creating objects
296. Student s1 = new Student(111,"Karan");
297. Student s2 = new Student(222,"Aryan");
298. Student s3 = new Student(333,"Sonoo");
299. //calling display method
300. s1.display();
301. s2.display();
302. s3.display();
303. }
304. }

Restrictions for the static method

There are two main restrictions for the static method. They are:

305. The static method can not use non static data member or call non-static
method directly.
306. this and super cannot be used in static context.

Why is the Java main method static?

Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of
extra memory allocation.

3) Java static block


• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.

this keyword in Java


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

307. this can be used to refer current class instance variable.


308. this can be used to invoke current class method (implicitly)
309. this() can be used to invoke current class constructor.
310. this can be passed as an argument in the method call.
311. this can be passed as argument in the constructor call.
312. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.

1) this: to refer current class instance variable

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

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:
313. class Student{
314. int rollno;
315. String name;
316. float fee;
317. Student(int rollno,String name,float fee){
318. rollno=rollno;
319. name=name;
320. fee=fee;
321. }
322. void display(){System.out.println(rollno+" "+name+" "+fee);}
323. }
324. class TestThis1{
325. public static void main(String args[]){
326. Student s1=new Student(111,"ankit",5000f);
327. Student s2=new Student(112,"sumit",6000f);
328. s1.display();
329. s2.display();
330. }}

this: to invoke current class method

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

The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized construct

Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword

this keyword can be used to return current class instance

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

Inheritance in Java
• Inheritance
• Types of Inheritance
• Why multiple inheritance is not possible in Java in case of class?

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


ADVERTISEMENT
ADVERTISEMENT

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


• For Code Reusability.
Terms used in Inheritance

• Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

331. class Subclass-name extends Superclass-name


332. {
333. //methods and fields
334. }

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.

335. class Employee{


336. float salary=40000;
337. }
338. class Programmer extends Employee{
339. int bonus=10000;
340. public static void main(String args[]){
341. Programmer p=new Programmer();
342. System.out.println("Programmer salary is:"+p.salary);
343. System.out.println("Bonus of Programmer is:"+p.bonus);
344. }
345. }
Test it Now
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:
ADVERTISEMENT
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

346. class Animal{


347. void eat(){System.out.println("eating...");}
348. }
349. class Dog extends Animal{
350. void bark(){System.out.println("barking...");}
351. }
352. class TestInheritance{
353. public static void main(String args[]){
354. Dog d=new Dog();
355. d.bark();
356. d.eat();
357. }}

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.

File: TestInheritance2.java

358. class Animal{


359. void eat(){System.out.println("eating...");}
360. }
361. class Dog extends Animal{
362. void bark(){System.out.println("barking...");}
363. }
364. class BabyDog extends Dog{
365. void weep(){System.out.println("weeping...");}
366. }
367. class TestInheritance2{
368. public static void main(String args[]){
369. BabyDog d=new BabyDog();
370. d.weep();
371. d.bark();
372. d.eat();
373. }}

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

374. class Animal{


375. void eat(){System.out.println("eating...");}
376. }
377. class Dog extends Animal{
378. void bark(){System.out.println("barking...");}
379. }
380. class Cat extends Animal{
381. void meow(){System.out.println("meowing...");}
382. }
383. class TestInheritance3{
384. public static void main(String args[]){
385. Cat c=new Cat();
386. c.meow();
387. c.eat();
388. //c.bark();//C.T.Error
389. }}

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.
390. class A{
391. void msg(){System.out.println("Hello");}
392. }
393. class B{
394. void msg(){System.out.println("Welcome");}
395. }
396. class C extends A,B{//suppose if it were
397.
398. public static void main(String args[]){
399. C obj=new C();
400. obj.msg();//Now which msg() method would be invoked?
401. }
402. }

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-
A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such as
city, state, country, zipcode etc. as given below.

403. class Employee{


404. int id;
405. String name;
406. Address address;//Address is a class
407. ...
408. }

In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

Why use Aggregation?


ADVERTISEMENT
ADVERTISEMENT

• For Code Reusability.


Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

409. class Operation{


410. int square(int n){
411. return n*n;
412. }
413. }
414.
415. class Circle{
416. Operation op;//aggregation
417. double pi=3.14;
418.
419. double area(int radius){
420. op=new Operation();
421. int rsquare=op.square(radius);//code reusability (i.e. delegates the method
call).
422. return pi*rsquare;
423. }
424.
425.
426.
427. public static void main(String args[]){
428. Circle c=new Circle();
429. double result=c.area(5);
430. System.out.println(result);
431. }
432. }
Test it Now

Output:78.5

When use Aggregation?

• Code reuse is also best achieved by aggregation when there is no is-a relationship.
• Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation

In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.

Address.java

433. public class Address {


434. String city,state,country;
435.
436. public Address(String city, String state, String country) {
437. this.city = city;
438. this.state = state;
439. this.country = country;
440. }
441.
442. }

Emp.java

443. public class Emp {


444. int id;
445. String name;
446. Address address;
447.
448. public Emp(int id, String name,Address address) {
449. this.id = id;
450. this.name = name;
451. this.address=address;
452. }
453.
454. void display(){
455. System.out.println(id+" "+name);
456. System.out.println(address.city+" "+address.state+" "+address.country);
457. }
458.
459. public static void main(String[] args) {
460. Address address1=new Address("gzb","UP","india");
461. Address address2=new Address("gno","UP","india");
462.
463. Emp e=new Emp(111,"varun",address1);
464. Emp e2=new Emp(112,"arun",address2);
465.
466. e.display();
467. e2.display();
468.
469. }
470. }

Method Overloading in Java


• Different ways to overload the method
• By changing the no. of arguments
• By changing the datatype
• Why method overloading is not possible by changing the return type
• Can we overload the main method
• method overloading with Type Promotion

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

471. By changing number of arguments


472. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

473. class Adder{


474. static int add(int a,int b){return a+b;}
475. static int add(int a,int b,int c){return a+b+c;}
476. }
477. class TestOverloading1{
478. public static void main(String[] args){
479. System.out.println(Adder.add(11,11));
480. System.out.println(Adder.add(11,11,11));
481. }}
Test it Now

Output:

22
33

2) Method Overloading: changing data type of arguments

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

482. class Adder{


483. static int add(int a, int b){return a+b;}
484. static double add(double a, double b){return a+b;}
485. }
486. class TestOverloading2{
487. public static void main(String[] args){
488. System.out.println(Adder.add(11,11));
489. System.out.println(Adder.add(12.3,12.6));
490. }}
Test it Now

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return


type of method only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

491. class Adder{


492. static int add(int a,int b){return a+b;}
493. static double add(int a,int b){return a+b;}
494. }
495. class TestOverloading3{
496. public static void main(String[] args){
497. System.out.println(Adder.add(11,11));//ambiguity
498. }}
Test it Now

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum()


method should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if
you declare the same method having same parameters.

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only.
Let's see the simple example:

499. class TestOverloading4{


500. public static void main(String[] args){System.out.println("main with
String[]");}
501. public static void main(String args){System.out.println("main with String");}
502. public static void main(){System.out.println("main without args");}
503. }
Test it Now

Output:

main with String[]

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int, long, float or double. The char datatype can be
promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion

504. class OverloadingCalculation1{


505. void sum(int a,long b){System.out.println(a+b);}
506. void sum(int a,int b,int c){System.out.println(a+b+c);}
507.
508. public static void main(String args[]){
509. OverloadingCalculation1 obj=new OverloadingCalculation1();
510. obj.sum(20,20);//now second int literal will be promoted to long
511. obj.sum(20,20,20);
512.
513. }
514. }
Test it Now
Output:40
60

Example of Method Overloading with Type Promotion if matching


found

If there are matching type arguments in the method, type promotion is not performed.

515. class OverloadingCalculation2{


516. void sum(int a,int b){System.out.println("int arg method invoked");}
517. void sum(long a,long b){System.out.println("long arg method invoked");}
518.
519. public static void main(String args[]){
520. OverloadingCalculation2 obj=new OverloadingCalculation2();
521. obj.sum(20,20);//now int arg sum() method gets invoked
522. }
523. }
Test it Now

Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of


ambiguity

If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

524. class OverloadingCalculation3{


525. void sum(int a,long b){System.out.println("a method invoked");}
526. void sum(long a,int b){System.out.println("b method invoked");}
527.
528. public static void main(String args[]){
529. OverloadingCalculation3 obj=new OverloadingCalculation3();
530. obj.sum(20,20);//now ambiguity
531. }
532. }

Method Overriding in Java


• Understanding the problem without method overriding
• Can we override the static method
• Method overloading vs. method overriding

If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


ADVERTISEMENT
ADVERTISEMENT

• Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

533. The method must have the same name as in the parent class
534. The method must have the same parameter as in the parent class.
535. 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.

536. //Java Program to demonstrate why we need method overriding


537. //Here, we are calling the method of parent class with child
538. //class object.
539. //Creating a parent class
540. class Vehicle{
541. void run(){System.out.println("Vehicle is running");}
542. }
543. //Creating a child class
544. class Bike extends Vehicle{
545. public static void main(String args[]){
546. //creating an instance of child class
547. Bike obj = new Bike();
548. //calling the method with child class instance
549. obj.run();
550. }
551. }
Test it Now

Output:

Vehicle is running

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

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method are
the same, and there is IS-A relationship between the classes, so there is method overriding.

552. //Java Program to illustrate the use of Java Method Overriding


553. //Creating a parent class.
554. class Vehicle{
555. //defining a method
556. void run(){System.out.println("Vehicle is running");}
557. }
558. //Creating a child class
559. class Bike2 extends Vehicle{
560. //defining the same method as in the parent class
561. void run(){System.out.println("Bike is running safely");}
562.
563. public static void main(String args[]){
564. Bike2 obj = new Bike2();//creating object
565. obj.run();//calling method
566. }
567. }
Test it Now

Output:
Bike is running safely

A real example of Java Method Overriding


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

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.

568. //Java Program to demonstrate the real scenario of Java Method Overriding
569. //where three classes are overriding the method of a parent class.
570. //Creating a parent class.
571. class Bank{
572. int getRateOfInterest(){return 0;}
573. }
574. //Creating child classes.
575. class SBI extends Bank{
576. int getRateOfInterest(){return 8;}
577. }
578.
579. class ICICI extends Bank{
580. int getRateOfInterest(){return 7;}
581. }
582. class AXIS extends Bank{
583. int getRateOfInterest(){return 9;}
584. }
585. //Test class to create objects and call the methods
586. class Test2{
587. public static void main(String args[]){
588. SBI s=new SBI();
589. ICICI i=new ICICI();
590. AXIS a=new AXIS();
591. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
592. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
593. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
594. }
595. }
Test it Now

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

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we


will learn it later.

Why can we not override static method?

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

Can we override java main method?

No, because the main is a static method.


Difference between method Overloading and Method
Overriding in java
Click me for the difference between method overloading and overriding

More topics on Method Overriding (Not For Beginners)

Method Overriding with Access Modifier

Let's see the concept of method overriding with access modifier.

Exception Handling with Method Overriding

Let's see the concept of method overriding with exception handling.

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

596. super can be used to refer immediate parent class instance variable.
597. super can be used to invoke immediate parent class method.
598. 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.

599. class Animal{


600. String color="white";
601. }
602. class Dog extends Animal{
603. String color="black";
604. void printColor(){
605. System.out.println(color);//prints color of Dog class
606. System.out.println(super.color);//prints color of Animal class
607. }
608. }
609. class TestSuper1{
610. public static void main(String args[]){
611. Dog d=new Dog();
612. d.printColor();
613. }}
Test it Now

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.

614. class Animal{


615. void eat(){System.out.println("eating...");}
616. }
617. class Dog extends Animal{
618. void eat(){System.out.println("eating bread...");}
619. void bark(){System.out.println("barking...");}
620. void work(){
621. super.eat();
622. bark();
623. }
624. }
625. class TestSuper2{
626. public static void main(String args[]){
627. Dog d=new Dog();
628. d.work();
629. }}
Test it Now

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:

630. class Animal{


631. Animal(){System.out.println("animal is created");}
632. }
633. class Dog extends Animal{
634. Dog(){
635. super();
636. System.out.println("dog is created");
637. }
638. }
639. class TestSuper3{
640. public static void main(String args[]){
641. Dog d=new Dog();
642. }}
Test it Now

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.

643. class Animal{


644. Animal(){System.out.println("animal is created");}
645. }
646. class Dog extends Animal{
647. Dog(){
648. System.out.println("dog is created");
649. }
650. }
651. class TestSuper4{
652. public static void main(String args[]){
653. Dog d=new Dog();
654. }}
Test it Now

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.

655. class Person{


656. int id;
657. String name;
658. Person(int id,String name){
659. this.id=id;
660. this.name=name;
661. }
662. }
663. class Emp extends Person{
664. float salary;
665. Emp(int id,String name,float salary){
666. super(id,name);//reusing parent constructor
667. this.salary=salary;
668. }
669. void display(){System.out.println(id+" "+name+" "+salary);}
670. }
671. class TestSuper5{
672. public static void main(String[] args){
673. Emp e1=new Emp(1,"ankit",45000f);
674. e1.display();
675. }}

Instance initializer block


• Instance initializer block
• Example of Instance initializer block
• What is invoked firstly instance initializer block or constructor?
• Rules for instance initializer block
• Program of instance initializer block that is invoked after super()
Instance Initializer block is used to initialize the instance data member. It run each time
when object of the class is created.
The initialization of the instance variable can be done directly but there can be performed
extra operations while initializing the instance variable in the instance initializer block.

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

676. class Bike{


677. int speed=100;
678. }

Why use instance initializer block?


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

Final Keyword In Java


• Final variable
• Final method
• Final class
• Is final method inherited ?
• Blank final variable
• Static blank final variable
• Final parameter
• Can you declare a final constructor

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

679. variable
680. method
681. 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.

682. class Bike9{


683. final int speedlimit=90;//final variable
684. void run(){
685. speedlimit=400;
686. }
687. public static void main(String args[]){
688. Bike9 obj=new Bike9();
689. obj.run();
690. }
691. }//end of class
Test it Now

Output:Compile Time Error

2) Java final method


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

Example of final method

692. class Bike{


693. final void run(){System.out.println("running");}
694. }
695.
696. class Honda extends Bike{
697. void run(){System.out.println("running safely with 100kmph");}
698.
699. public static void main(String args[]){
700. Honda honda= new Honda();
701. honda.run();
702. }
703. }
Test it Now

Output:Compile Time Error

3) Java final class


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

Example of final class

704. final class Bike{}


705.
706. class Honda1 extends Bike{
707. void run(){System.out.println("running safely with 100kmph");}
708.
709. public static void main(String args[]){
710. Honda1 honda= new Honda1();
711. honda.run();
712. }
713. }
Test it Now

Output:Compile Time Error

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

714. class Bike{


715. final void run(){System.out.println("running...");}
716. }
717. class Honda2 extends Bike{
718. public static void main(String args[]){
719. new Honda2().run();
720. }
721. }
Test it Now

Output:running...

Q) What is blank or uninitialized final variable?

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

It can be initialized only in constructor.

Example of blank final variable

722. class Student{


723. int id;
724. String name;
725. final String PAN_CARD_NUMBER;
726. ...
727. }

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

728. class Bike10{


729. final int speedlimit;//blank final variable
730.
731. Bike10(){
732. speedlimit=70;
733. System.out.println(speedlimit);
734. }
735.
736. public static void main(String args[]){
737. new Bike10();
738. }
739. }
Test it Now

Output: 70
static blank final variable

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

Example of static blank final variable

740. class A{
741. static final int data;//static blank final variable
742. static{ data=50;}
743. public static void main(String args[]){
744. System.out.println(A.data);
745. }
746. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

747. class Bike11{


748. int cube(final int n){
749. n=n+2;//can't be changed as n is final
750. n*n*n;
751. }
752. public static void main(String args[]){
753. Bike11 b=new Bike11();
754. b.cube(5);
755. }
756. }
Test it Now

Output: Compile Time Error


Q) Can we declare a constructor final?

No, because constructor is never inherited.

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
757. class A{}
758. class B extends A{}
759. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For
Example:

760. interface I{}


761. class A{}
762. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.
ADVERTISEMENT

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable
of Parent class. Since it refers to the subclass object and subclass method overrides the
Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
763. class Bike{
764. void run(){System.out.println("running");}
765. }
766. class Splendor extends Bike{
767. void run(){System.out.println("running safely with 60km");}
768.
769. public static void main(String args[]){
770. Bike b = new Splendor();//upcasting
771. b.run();
772. }
773. }
Test it Now

Output:

running safely with 60km.

Java Runtime Polymorphism Example: Bank


Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS
banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

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

774. class Bank{


775. float getRateOfInterest(){return 0;}
776. }
777. class SBI extends Bank{
778. float getRateOfInterest(){return 8.4f;}
779. }
780. class ICICI extends Bank{
781. float getRateOfInterest(){return 7.3f;}
782. }
783. class AXIS extends Bank{
784. float getRateOfInterest(){return 9.7f;}
785. }
786. class TestPolymorphism{
787. public static void main(String args[]){
788. Bank b;
789. b=new SBI();
790. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
791. b=new ICICI();
792. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
793. b=new AXIS();
794. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
795. }
796. }
Test it Now

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape


797. class Shape{
798. void draw(){System.out.println("drawing...");}
799. }
800. class Rectangle extends Shape{
801. void draw(){System.out.println("drawing rectangle...");}
802. }
803. class Circle extends Shape{
804. void draw(){System.out.println("drawing circle...");}
805. }
806. class Triangle extends Shape{
807. void draw(){System.out.println("drawing triangle...");}
808. }
809. class TestPolymorphism2{
810. public static void main(String args[]){
811. Shape s;
812. s=new Rectangle();
813. s.draw();
814. s=new Circle();
815. s.draw();
816. s=new Triangle();
817. s.draw();
818. }
819. }
Test it Now

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal


820. class Animal{
821. void eat(){System.out.println("eating...");}
822. }
823. class Dog extends Animal{
824. void eat(){System.out.println("eating bread...");}
825. }
826. class Cat extends Animal{
827. void eat(){System.out.println("eating rat...");}
828. }
829. class Lion extends Animal{
830. void eat(){System.out.println("eating meat...");}
831. }
832. class TestPolymorphism3{
833. public static void main(String[] args){
834. Animal a;
835. a=new Dog();
836. a.eat();
837. a=new Cat();
838. a.eat();
839. a=new Lion();
840. a.eat();
841. }}
Test it Now

Output:
ADVERTISEMENT

eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism can't be achieved
by data members.

In the example given below, both the classes have a data member speedlimit. We are
accessing the data member by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the data member which is not overridden, hence it
will access the data member of the Parent class always.

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

842. class Bike{


843. int speedlimit=90;
844. }
845. class Honda3 extends Bike{
846. int speedlimit=150;
847.
848. public static void main(String args[]){
849. Bike obj=new Honda3();
850. System.out.println(obj.speedlimit);//90
851. }
Test it Now

Output:

90

Java Runtime Polymorphism with Multilevel Inheritance


Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

852. class Animal{


853. void eat(){System.out.println("eating");}
854. }
855. class Dog extends Animal{
856. void eat(){System.out.println("eating fruits");}
857. }
858. class BabyDog extends Dog{
859. void eat(){System.out.println("drinking milk");}
860. public static void main(String args[]){
861. Animal a1,a2,a3;
862. a1=new Animal();
863. a2=new Dog();
864. a3=new BabyDog();
865. a1.eat();
866. a2.eat();
867. a3.eat();
868. }
869. }
Test it Now

Output:

eating
eating fruits
drinking Milk

Try for Output

870. class Animal{


871. void eat(){System.out.println("animal is eating...");}
872. }
873. class Dog extends Animal{
874. void eat(){System.out.println("dog is eating...");}
875. }
876. class BabyDog1 extends Dog{
877. public static void main(String args[]){
878. Animal a=new BabyDog1();
879. a.eat();
880. }}

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

881. Static Binding (also known as Early Binding).


882. Dynamic Binding (also known as Late Binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

883. int data=30;

Here data variable is a type of int.

2) References have a type

884. class Dog{


885. public static void main(String args[]){
886. Dog d1;//Here d1 is a type of Dog
887. }
888. }
3) Objects have a type

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


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

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static
binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding

896. class Dog{


897. private void eat(){System.out.println("dog is eating...");}
898.
899. public static void main(String args[]){
900. Dog d1=new Dog();
901. d1.eat();
902. }
903. }

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

904. class Animal{


905. void eat(){System.out.println("animal is eating...");}
906. }
907.
908. class Dog extends Animal{
909. void eat(){System.out.println("dog is eating...");}
910.
911. public static void main(String args[]){
912. Animal a=new Dog();
913. a.eat();
914. }
915. }

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

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


916. Abstract class (0 to 100%)
917. 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

ADVERTISEMENT
ADVERTISEMENT

• An abstract class must be declared with an abstract keyword.


• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class


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


ADVERTISEMENT

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

920. abstract class Bike{


921. abstract void run();
922. }
923. class Honda4 extends Bike{
924. void run(){System.out.println("running safely");}
925. public static void main(String args[]){
926. Bike obj = new Honda4();
927. obj.run();
928. }
929. }
Test it Now

running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and
an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.

File: TestAbstraction1.java

930. abstract class Shape{


931. abstract void draw();
932. }
933. //In real scenario, implementation is provided by others i.e. unknown by end
user
934. class Rectangle extends Shape{
935. void draw(){System.out.println("drawing rectangle");}
936. }
937. class Circle1 extends Shape{
938. void draw(){System.out.println("drawing circle");}
939. }
940. //In real scenario, method is called by programmer or user
941. class TestAbstraction1{
942. public static void main(String args[]){
943. Shape s=new Circle1();//In a real scenario, object is provided through
method, e.g., getShape() method
944. s.draw();
945. }
946. }
Test it Now

drawing circle

Another example of Abstract class in java


File: TestBank.java
ADVERTISEMENT

947. abstract class Bank{


948. abstract int getRateOfInterest();
949. }
950. class SBI extends Bank{
951. int getRateOfInterest(){return 7;}
952. }
953. class PNB extends Bank{
954. int getRateOfInterest(){return 8;}
955. }
956.
957. class TestBank{
958. public static void main(String args[]){
959. Bank b;
960. b=new SBI();
961. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
962. b=new PNB();
963. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
964. }}
Test it Now

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Abstract class having constructor, data member and


methods
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.

File: TestAbstraction2.java

965. //Example of an abstract class that has abstract and non-abstract methods
966. abstract class Bike{
967. Bike(){System.out.println("bike is created");}
968. abstract void run();
969. void changeGear(){System.out.println("gear changed");}
970. }
971. //Creating a Child class which inherits Abstract class
972. class Honda extends Bike{
973. void run(){System.out.println("running safely..");}
974. }
975. //Creating a Test class which calls abstract and non-abstract methods
976. class TestAbstraction2{
977. public static void main(String args[]){
978. Bike obj = new Honda();
979. obj.run();
980. obj.changeGear();
981. }
982. }
Test it Now

bike is created
running safely..
gear changed

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

983. class Bike12{


984. abstract void run();
985. }
Test it Now

compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

986. interface A{
987. void a();
988. void b();
989. void c();
990. void d();
991. }
992.
993. abstract class B implements A{
994. public void c(){System.out.println("I am c");}
995. }
996.
997. class M extends B{
998. public void a(){System.out.println("I am a");}
999. public void b(){System.out.println("I am b");}
1000. public void d(){System.out.println("I am d");}
1001. }
1002.
1003. class Test5{
1004. public static void main(String args[]){
1005. A a=new M();
1006. a.a();
1007. a.b();
1008. a.c();
1009. a.d();
1010. }}
Next »« Prev
Interface in Java
• Interface
• Example of Interface
• Multiple inheritance by Interface
• Why multiple inheritance is supported in Interface while it is not supported in case of class.
• Marker Interface
• Nested Interface

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

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

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

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


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

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
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:

1011. interface <interface_name>{


1012.
1013. // declare constant fields
1014. // declare methods that abstract
1015. // by default.
1016. }

Java 8 Interface Improvement


Since Java 8, interface can have default and static methods which is discussed later.
ADVERTISEMENT
ADVERTISEMENT

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.

The relationship between classes and interfaces

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

ADVERTISEMENT
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

1017. interface printable{


1018. void print();
1019. }
1020. class A6 implements printable{
1021. public void print(){System.out.println("Hello");}
1022.
1023. public static void main(String args[]){
1024. A6 obj = new A6();
1025. obj.print();
1026. }
1027. }
Test it Now

Output:

Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else,
but its implementation is provided by different implementation providers. Moreover, it is
used by someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

1028. //Interface declaration: by first user


1029. interface Drawable{
1030. void draw();
1031. }
1032. //Implementation: by second user
1033. class Rectangle implements Drawable{
1034. public void draw(){System.out.println("drawing rectangle");}
1035. }
1036. class Circle implements Drawable{
1037. public void draw(){System.out.println("drawing circle");}
1038. }
1039. //Using interface: by third user
1040. class TestInterface1{
1041. public static void main(String args[]){
1042. Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()
1043. d.draw();
1044. }}
Test it Now

Output:

drawing circle

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java

1045. interface Bank{


1046. float rateOfInterest();
1047. }
1048. class SBI implements Bank{
1049. public float rateOfInterest(){return 9.15f;}
1050. }
1051. class PNB implements Bank{
1052. public float rateOfInterest(){return 9.7f;}
1053. }
1054. class TestInterface2{
1055. public static void main(String[] args){
1056. Bank b=new SBI();
1057. System.out.println("ROI: "+b.rateOfInterest());
1058. }}
Test it Now

Output:
ADVERTISEMENT

ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

1059. interface Printable{


1060. void print();
1061. }
1062. interface Showable{
1063. void show();
1064. }
1065. class A7 implements Printable,Showable{
1066. public void print(){System.out.println("Hello");}
1067. public void show(){System.out.println("Welcome");}
1068.
1069. public static void main(String args[]){
1070. A7 obj = new A7();
1071. obj.print();
1072. obj.show();
1073. }
1074. }
Test it Now

Output:Hello
Welcome

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


possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation
class. For example:

1075. interface Printable{


1076. void print();
1077. }
1078. interface Showable{
1079. void print();
1080. }
1081.
1082. class TestInterface3 implements Printable, Showable{
1083. public void print(){System.out.println("Hello");}
1084. public static void main(String args[]){
1085. TestInterface3 obj = new TestInterface3();
1086. obj.print();
1087. }
1088. }
Test it Now
ADVERTISEMENT
ADVERTISEMENT

Output:
Hello

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

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

1089. interface Printable{


1090. void print();
1091. }
1092. interface Showable extends Printable{
1093. void show();
1094. }
1095. class TestInterface4 implements Showable{
1096. public void print(){System.out.println("Hello");}
1097. public void show(){System.out.println("Welcome");}
1098.
1099. public static void main(String args[]){
1100. TestInterface4 obj = new TestInterface4();
1101. obj.print();
1102. obj.show();
1103. }
1104. }
Test it Now

Output:

Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:

File: TestInterfaceDefault.java

1105. interface Drawable{


1106. void draw();
1107. default void msg(){System.out.println("default method");}
1108. }
1109. class Rectangle implements Drawable{
1110. public void draw(){System.out.println("drawing rectangle");}
1111. }
1112. class TestInterfaceDefault{
1113. public static void main(String args[]){
1114. Drawable d=new Rectangle();
1115. d.draw();
1116. d.msg();
1117. }}
Test it Now

Output:

drawing rectangle
default method

Java 8 Static Method in Interface


Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1118. interface Drawable{


1119. void draw();
1120. static int cube(int x){return x*x*x;}
1121. }
1122. class Rectangle implements Drawable{
1123. public void draw(){System.out.println("drawing rectangle");}
1124. }
1125.
1126. class TestInterfaceStatic{
1127. public static void main(String args[]){
1128. Drawable d=new Rectangle();
1129. d.draw();
1130. System.out.println(Drawable.cube(3));
1131. }}
Test it Now

Output:

drawing rectangle
27

Q) What is marker or tagged interface?


An interface which has no member is known as a marker or tagged interface, for example,
Serializable, Cloneable, Remote, etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.

1132. //How Serializable interface is written?


1133. public interface Serializable{
1134. }

Nested Interface in Java

Note: An interface can have another interface which is known as a nested interface. We will
learn it in detail in the nested classes chapter. For example:

1135. interface printable{


1136. void print();
1137. interface MessagePrintable{
1138. void msg();
1139. }
1140. }

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

Example of abstract class and interface in Java


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

1141. //Creating interface that has 4 methods


1142. interface A{
1143. void a();//bydefault, public and abstract
1144. void b();
1145. void c();
1146. void d();
1147. }
1148.
1149. //Creating abstract class that provides the implementation of one method of
A interface
1150. abstract class B implements A{
1151. public void c(){System.out.println("I am C");}
1152. }
1153.
1154. //Creating subclass of abstract class, now we need to provide the
implementation of rest of the methods
1155. class M extends B{
1156. public void a(){System.out.println("I am a");}
1157. public void b(){System.out.println("I am b");}
1158. public void d(){System.out.println("I am d");}
1159. }
1160.
1161. //Creating a test class that calls the methods of A interface
1162. class Test5{
1163. public static void main(String args[]){
1164. A a=new M();
1165. a.a();
1166. a.b();
1167. a.c();
1168. a.d();
1169. }}

Java Package
• Java Package
• Example of package
• Accessing package
o By import packagename.*
o By import packagename.classname
o By fully qualified name
• Subpackage
• Sending class file to another directory
• -classpath switch
• 4 ways to load the class file or jar file
• How to put two public class in a package
• Static Import
• Package class

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

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.

1170. //save as Simple.java


1171. package mypack;
1172. public class Simple{
1173. public static void main(String args[]){
1174. System.out.println("Welcome to package");
1175. }
1176. }

How to compile java package

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

1177. javac -d directory javafilename

For example
ADVERTISEMENT
ADVERTISEMENT

1178. javac -d . Simple.java


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

How to run java package program

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

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package

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

Access Modifiers in Java


• Private access modifier
• Role of private constructor
• Default access modifier
• Protected access modifier
• Public access modifier
• Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.

There are four types of Java access modifiers:

1179. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
1180. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the default.
1181. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
1182. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.

ADVERTISEMENT
ADVERTISEMENT

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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

Simple example of private access modifier

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

1183. class A{
1184. private int data=40;
1185. private void msg(){System.out.println("Hello java");}
1186. }
1187.
1188. public class Simple{
1189. public static void main(String args[]){
1190. A obj=new A();
1191. System.out.println(obj.data);//Compile Time Error
1192. obj.msg();//Compile Time Error
1193. }
1194. }

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:

1195. class A{
1196. private A(){}//private constructor
1197. void msg(){System.out.println("Hello java");}
1198. }
1199. public class Simple{
1200. public static void main(String args[]){
1201. A obj=new A();//Compile Time Error
1202. }
1203. }

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

2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.

Example of default access modifier


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

1204. //save by A.java


1205. package pack;
1206. class A{
1207. void msg(){System.out.println("Hello");}
1208. }
1209. //save by B.java
1210. package mypack;
1211. import pack.*;
1212. class B{
1213. public static void main(String args[]){
1214. A obj = new A();//Compile Time Error
1215. obj.msg();//Compile Time Error
1216. }
1217. }

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

ADVERTISEMENT

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

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

Example of public access modifier

1233. //save by A.java


1234.
1235. package pack;
1236. public class A{
1237. public void msg(){System.out.println("Hello");}
1238. }
1239. //save by B.java
1240.
1241. package mypack;
1242. import pack.*;
1243.
1244. class B{
1245. public static void main(String args[]){
1246. A obj = new A();
1247. obj.msg();
1248. }
1249. }
Output:Hello

Java Access Modifiers with Method Overriding


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

1250. class A{
1251. protected void msg(){System.out.println("Hello java");}
1252. }
1253.
1254. public class Simple extends A{
1255. void msg(){System.out.println("Hello java");}//C.T.Error
1256. public static void main(String args[]){
1257. Simple obj=new Simple();
1258. obj.msg();
1259. }
1260. }

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

Next TopicEncapsulation in Java

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

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java

By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.
ADVERTISEMENT

It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy
and fast to create an encapsulated class in Java.

Simple Example of Encapsulation in Java


Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.

File: Student.java

1261. //A Java class which is a fully encapsulated class.


1262. //It has a private data member and getter and setter methods.
1263. package com.javatpoint;
1264. public class Student{
1265. //private data member
1266. private String name;
1267. //getter method for name
1268. public String getName(){
1269. return name;
1270. }
1271. //setter method for name
1272. public void setName(String name){
1273. this.name=name
1274. }
1275. }

File: Test.java

1276. //A Java class to test the encapsulated class.


1277. package com.javatpoint;
1278. class Test{
1279. public static void main(String[] args){
1280. //creating instance of the encapsulated class
1281. Student s=new Student();
1282. //setting value in the name member
1283. s.setName("vijay");
1284. //getting value of the name member
1285. System.out.println(s.getName());
1286. }
1287. }
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test

Output:

vijay

Read-Only class

1288. //A Java class which has only getter methods.


1289. public class Student{
1290. //private data member
1291. private String college="AKG";
1292. //getter method for college
1293. public String getCollege(){
1294. return college;
1295. }
1296. }

Now, you can't change the value of the college data member which is "AKG".

1297. s.setCollege("KITE");//will render compile time error

Write-Only class

1298. //A Java class which has only setter methods.


1299. public class Student{
1300. //private data member
1301. private String college;
1302. //getter method for college
1303. public void setCollege(String college){
1304. this.college=college;
1305. }
1306. }

Now, you can't get the value of the college, you can only change the value of college data
member.

1307. System.out.println(s.getCollege());//Compile Time Error, because there is no


such method
1308. System.out.println(s.college);//Compile Time Error, because the college data
member is private.
1309. //So, it can't be accessed from outside the class

Another Example of Encapsulation in Java

Let's see another example of encapsulation that has only four fields with its setter and getter
methods.
File: Account.java

1310. //A Account class which is a fully encapsulated class.


1311. //It has a private data member and getter and setter methods.
1312. class Account {
1313. //private data members
1314. private long acc_no;
1315. private String name,email;
1316. private float amount;
1317. //public getter and setter methods
1318. public long getAcc_no() {
1319. return acc_no;
1320. }
1321. public void setAcc_no(long acc_no) {
1322. this.acc_no = acc_no;
1323. }
1324. public String getName() {
1325. return name;
1326. }
1327. public void setName(String name) {
1328. this.name = name;
1329. }
1330. public String getEmail() {
1331. return email;
1332. }
1333. public void setEmail(String email) {
1334. this.email = email;
1335. }
1336. public float getAmount() {
1337. return amount;
1338. }
1339. public void setAmount(float amount) {
1340. this.amount = amount;
1341. }
1342.
1343. }

File: TestAccount.java

1344. //A Java class to test the encapsulated class Account.


1345. public class TestEncapsulation {
1346. public static void main(String[] args) {
1347. //creating instance of Account class
1348. Account acc=new Account();
1349. //setting values through setter methods
1350. acc.setAcc_no(7560504000L);
1351. acc.setName("Sonoo Jaiswal");
1352. acc.setEmail("[email protected]");
1353. acc.setAmount(500000f);
1354. //getting values through getter methods
1355. System.out.println(acc.getAcc_no()+" "+acc.getName()+"
"+acc.getEmail()+" "+acc.getAmount());
1356. }
1357. }

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:

1358. 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.
ADVERTISEMENT
ADVERTISEMENT
Methods of Object class
The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's
monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.

public final void wait(long causes the current thread to wait for the specified
timeout)throws milliseconds, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
public final void wait(long causes the current thread to wait for the specified
timeout,int nanos)throws milliseconds and nanoseconds, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).

public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).

protected void finalize()throws is invoked by the garbage collector before object


Throwable is being garbage collected.

Object Cloning in Java

The object cloning is a way to create


exact copy of an object. The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios,
where we need to use the wrapper classes.
ADVERTISEMENT
ADVERTISEMENT

• Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal with
objects.
• Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer
long Long

float Float

double Double

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

Wrapper class Example: Primitive to Wrapper

1359. //Java program to convert primitive into objects


1360. //Autoboxing example of int to Integer
1361. public class WrapperExample1{
1362. public static void main(String args[]){
1363. //Converting int into Integer
1364. int a=20;
1365. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
1366. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a)
internally
1367.
1368. System.out.println(a+" "+i+" "+j);
1369. }}

Output:

20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive

1370. //Java program to convert object into primitives


1371. //Unboxing example of Integer to int
1372. public class WrapperExample2{
1373. public static void main(String args[]){
1374. //Converting Integer to int
1375. Integer a=new Integer(3);
1376. int i=a.intValue();//converting Integer to int explicitly
1377. int j=a;//unboxing, now compiler will write a.intValue() internally
1378.
1379. System.out.println(a+" "+i+" "+j);
1380. }}

Output:

3 3 3

Java Wrapper classes Example


1381. //Java Program to convert all primitives into its corresponding
1382. //wrapper objects and vice-versa
1383. public class WrapperExample3{
1384. public static void main(String args[]){
1385. byte b=10;
1386. short s=20;
1387. int i=30;
1388. long l=40;
1389. float f=50.0F;
1390. double d=60.0D;
1391. char c='a';
1392. boolean b2=true;
1393.
1394. //Autoboxing: Converting primitives into objects
1395. Byte byteobj=b;
1396. Short shortobj=s;
1397. Integer intobj=i;
1398. Long longobj=l;
1399. Float floatobj=f;
1400. Double doubleobj=d;
1401. Character charobj=c;
1402. Boolean boolobj=b2;
1403.
1404. //Printing objects
1405. System.out.println("---Printing object values---");
1406. System.out.println("Byte object: "+byteobj);
1407. System.out.println("Short object: "+shortobj);
1408. System.out.println("Integer object: "+intobj);
1409. System.out.println("Long object: "+longobj);
1410. System.out.println("Float object: "+floatobj);
1411. System.out.println("Double object: "+doubleobj);
1412. System.out.println("Character object: "+charobj);
1413. System.out.println("Boolean object: "+boolobj);
1414.
1415. //Unboxing: Converting Objects to Primitives
1416. byte bytevalue=byteobj;
1417. short shortvalue=shortobj;
1418. int intvalue=intobj;
1419. long longvalue=longobj;
1420. float floatvalue=floatobj;
1421. double doublevalue=doubleobj;
1422. char charvalue=charobj;
1423. boolean boolvalue=boolobj;
1424.
1425. //Printing primitives
1426. System.out.println("---Printing primitive values---");
1427. System.out.println("byte value: "+bytevalue);
1428. System.out.println("short value: "+shortvalue);
1429. System.out.println("int value: "+intvalue);
1430. System.out.println("long value: "+longvalue);
1431. System.out.println("float value: "+floatvalue);
1432. System.out.println("double value: "+doublevalue);
1433. System.out.println("char value: "+charvalue);
1434. System.out.println("boolean value: "+boolvalue);
1435. }}

Output:

---Printing object values---


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

Custom Wrapper class in Java


Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper
classes. We can also create a class which wraps a primitive data type. So, we can create a
custom wrapper class in Java.
1436. //Creating the custom wrapper class
1437. class Javatpoint{
1438. private int i;
1439. Javatpoint(){}
1440. Javatpoint(int i){
1441. this.i=i;
1442. }
1443. public int getValue(){
1444. return i;
1445. }
1446. public void setValue(int i){
1447. this.i=i;
1448. }
1449. @Override
1450. public String toString() {
1451. return Integer.toString(i);
1452. }
1453. }
1454. //Testing the custom wrapper class
1455. public class TestJavatpoint{
1456. public static void main(String[] args){
1457. Javatpoint j=new Javatpoint(10);
1458. System.out.println(j);
1459. }}

Java Command Line Arguments


• Command Line Argument
• Simple example of command-line argument
• Example of command-line argument that prints all the values

The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

Difference between object and class


There are many differences between object and class. A list of differences between object
and class are given below:

N Object Class
o
.

1 Object is an instance of a class. Class is a blueprint or


) template from which
objects are created.

2 Object is a real world entity such as pen, laptop, Class is a group of similar
) mobile, bed, keyboard, mouse, chair etc. objects.

3 Object is a physical entity. Class is a logical entity.


)

4 Object is created through new keyword mainly e.g. Class is declared using class
) Student s1=new Student(); keyword e.g.
class Student{}

5 Object is created many times as per requirement. Class is declared once.


)

6 Object allocates memory when it is created. Class doesn't allocated


) memory when it is
created.

7 There are many ways to create object in java such as There is only one way to
) new keyword, newInstance() method, clone() method, define class in java using
factory method and deserialization. class keyword.
Let's see some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

Difference between method overloading and


method overriding in java
There are many differences between method overloading and method overriding in java. A
list of differences between method overloading and method overriding are given below:

N Method Overloading Method Overriding


o
.

1 Method overloading is used to increase the Method overriding is used to


) readability of the program. provide the specific
implementation of the method that
is already provided by its super
class.

2 Method overloading is performed within class. Method overriding occurs in two


) classes that have IS-A
(inheritance) relationship.

3 In case of method overloading, parameter must In case of method overriding,


) be different. parameter must be same.

4 Method overloading is the example of compile Method overriding is the example


) time polymorphism. of run time polymorphism.

5 In java, method overloading can't be performed Return type must be same or


) by changing return type of the method only. covariant in method overriding.
Return type can be same or different in method
overloading. But you must have to change the
parameter.
Java Method Overloading example
1460. class OverloadingExample{
1461. static int add(int a,int b){return a+b;}
1462. static int add(int a,int b,int c){return a+b+c;}
1463. }

Java Method Overriding example


1464. class Animal{
1465. void eat(){System.out.println("eating...");}
1466. }
1467. class Dog extends Animal{
1468. void eat(){System.out.println("eating bread...");}
1469. }

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1470. char[] ch={'j','a','v','a','t','p','o','i','n','t'};


1471. String s=new String(ch);

is same as:

1472. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

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

PauseNext
Unmute
Current Time 0:02
/
Duration 18:10
Loaded: 3.30%
Â
Fullscreen

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java
by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.

We will discuss immutable string later. Let's first understand what String in Java is and how
to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

1473. By string literal


1474. By new keyword

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

1475. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

1476. String s1="Welcome";


1477. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.

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

Why Java uses the concept of String literal?

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

2) By new keyword

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


variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Java String Example
StringExample.java

1479. public class StringExample{


1480. public static void main(String args[]){
1481. String s1="java";//creating string by Java string literal
1482. char ch[]={'s','t','r','i','n','g','s'};
1483. String s2=new String(ch);//converting char array to string
1484. String s3=new String("example");//creating Java string by new keyword
1485. System.out.println(s1);
1486. System.out.println(s2);
1487. System.out.println(s3);
1488. }}
Test it Now

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String objects
s1, s2, and s3 on console using println() method.

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence
of char values.

N Method Description
o
.

1 char charAt(int index) It returns char value for the


particular index
2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int endIndex) It returns substring for given


begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

1 boolean equals(Object another) It checks the equality of string


0 with the given object.

1 boolean isEmpty() It checks if string is empty.


1

1 String concat(String str) It concatenates the specified


2 string.

1 String replace(char old, char new) It replaces all occurrences of the


3 specified char value.

1 String replace(CharSequence old, CharSequence It replaces all occurrences of the


4 new) specified CharSequence.

1 static String equalsIgnoreCase(String another) It compares another string. It


5 doesn't check case.

1 String[] split(String regex) It returns a split string matching


6 regex.
1 String[] split(String regex, int limit) It returns a split string matching
7 regex and limit.

1 String intern() It returns an interned string.


8

1 int indexOf(int ch) It returns the specified char value


9 index.

2 int indexOf(int ch, int fromIndex) It returns the specified char value
0 index starting with given index.

2 int indexOf(String substring) It returns the specified substring


1 index.

2 int indexOf(String substring, int fromIndex) It returns the specified substring


2 index starting with given index.

2 String toLowerCase() It returns a string in lowercase.


3

2 String toLowerCase(Locale l) It returns a string in lowercase


4 using specified locale.

2 String toUpperCase() It returns a string in uppercase.


5

2 String toUpperCase(Locale l) It returns a string in uppercase


6 using specified locale.

2 String trim() It removes beginning and ending


7 spaces of this string.

2 static String valueOf(int value) It converts given type into string.


8 It is an overloaded method.

Immutable String in Java


A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is
created.

Let's try to understand the concept of immutability by the example given below:

Testimmutablestring.java

1489. class Testimmutablestring{


1490. public static void main(String args[]){
1491. String s="Sachin";
1492. s.concat(" Tendulkar");//concat() method appends the string at the end
1493. System.out.println(s);//will print Sachin because strings are immutable
objects
1494. }
1495. }
Test it Now

Output:

Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.

For example:

Testimmutablestring1.java

1496. class Testimmutablestring1{


1497. public static void main(String args[]){
1498. String s="Sachin";
1499. s=s.concat(" Tendulkar");
1500. System.out.println(s);
1501. }
1502. }
Test it Now

Output:

Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.

Why String objects are immutable in Java?

As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to
one object "Sachin". If one reference variable changes the value of the object, it will be
affected by all the reference variables. That is why String objects are immutable in Java.

Following are some features of String which makes String objects immutable.

1. ClassLoader:

A ClassLoader in Java uses a String object as an argument. Consider, if the String object is
modifiable, the value might be changed and the class that is supposed to be loaded might be
different.

To avoid this kind of misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further errors by loading
the correct class. This leads to making the application program more secure. Consider an
example of banking software. The username and password cannot be modified by any
intruder because String objects are immutable. This can make the application program more
secure.

4. Heap Space:

The immutability of String helps to minimize the usage in the heap memory. When we try to
declare a new String object, the JVM checks whether the value already exists in the String
pool or not. If it exists, the same value is assigned to the new object. This feature allows Java
to use the heap space efficiently.

Why String class is Final in Java?

The reason behind the String class being final is because no one can override the methods of
the String class. So that it can provide the same features to the new String objects as well as
to the old ones.
Java String compare

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method),


reference matching (by == operator) etc.

There are three ways to compare String in Java:

1503. By Using equals() Method


1504. By Using == Operator
1505. By compareTo() Method

1) By Using equals() Method


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

• public boolean equals(Object another) compares this string to the specified object.
• public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.

Teststringcomparison1.java

1506. class Teststringcomparison1{


1507. public static void main(String args[]){
1508. String s1="Sachin";
1509. String s2="Sachin";
1510. String s3=new String("Sachin");
1511. String s4="Saurav";
1512. System.out.println(s1.equals(s2));//true
1513. System.out.println(s1.equals(s3));//true
1514. System.out.println(s1.equals(s4));//false
1515. }
1516. }
Test it Now

Output:

true
true
false

In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.

Teststringcomparison2.java

1517. class Teststringcomparison2{


1518. public static void main(String args[]){
1519. String s1="Sachin";
1520. String s2="SACHIN";
1521.
1522. System.out.println(s1.equals(s2));//false
1523. System.out.println(s1.equalsIgnoreCase(s2));//true
1524. }
1525. }
Test it Now

Output:

false
true
In the above program, the methods of String class are used. The equals() method returns
true if String objects are matching and both strings are of same case. equalsIgnoreCase()
returns true regardless of cases of strings.

Click here for more about equals() method

2) By Using == operator
The == operator compares references not values.

Teststringcomparison3.java

1526. class Teststringcomparison3{


1527. public static void main(String args[]){
1528. String s1="Sachin";
1529. String s2="Sachin";
1530. String s3=new String("Sachin");
1531. System.out.println(s1==s2);//true (because both refer to same instance)
1532. System.out.println(s1==s3);//false(because s3 refers to instance created in
nonpool)
1533. }
1534. }
Test it Now

Output:

true
false

3) String compare by compareTo() method


The above code, demonstrates the use of == operator used for comparing two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

• s1 == s2 : The method returns 0.


• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.

Teststringcomparison4.java

1535. class Teststringcomparison4{


1536. public static void main(String args[]){
1537. String s1="Sachin";
1538. String s2="Sachin";
1539. String s3="Ratan";
1540. System.out.println(s1.compareTo(s2));//0
1541. System.out.println(s1.compareTo(s3));//1(because s1>s3)
1542. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
1543. }
1544. }

String Concatenation in Java


In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:

1545. By + (String concatenation) operator


1546. By concat() method

1) String Concatenation by + (String concatenation)


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

TestStringConcatenation1.java
1547. class TestStringConcatenation1{
1548. public static void main(String args[]){
1549. String s="Sachin"+" Tendulkar";
1550. System.out.println(s);//Sachin Tendulkar
1551. }
1552. }

Substring in Java
A part of String is called substring. In other words, substring is a subset of another String.
Java String class provides the built-in substring() method that extract a substring from the
given string by using the index values passed as an argument. In case of substring() method
startIndex is inclusive and endIndex is exclusive.

Suppose the string is "computer", then the substring will be com, compu, ter, etc.

Note: Index starts from 0.

You can get substring from the given String object by one of the two methods:

1553. public String substring(int startIndex):


This method returns new String object containing the substring of the given string
from specified startIndex (inclusive). The method throws an
IndexOutOfBoundException when the startIndex is larger than the length of String or
less than zero.
1554. public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string
from specified startIndex to endIndex. The method throws an
IndexOutOfBoundException when the startIndex is less than zero or startIndex is
greater than endIndex or endIndex is greater than length of String.

In case of String:

• startIndex: inclusive
• endIndex: exclusive

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

1555. String s="hello";


1556. System.out.println(s.substring(0,2)); //returns he as a substring

In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because
end index is exclusive).

Example of Java substring() method

TestSubstring.java

1557. public class TestSubstring{


1558. public static void main(String args[]){
1559. String s="SachinTendulkar";
1560. System.out.println("Original String: " + s);
1561. System.out.println("Substring starting from index 6: "
+s.substring(6));//Tendulkar
1562. System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6));
//Sachin
1563. }
1564. }

Output:

Java String Class Methods


The java.lang.String class provides a lot of built-in methods that are used to manipulate string in
Java. By the help of these methods, we can perform operations on String objects such as trimming,
concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a String if you submit any form in
window based, web based or mobile application.

Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method


The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is
safe and will result in an order.

Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String It creates a String buffer with the specified string..


str)

StringBuffer(int It creates an empty String buffer with the specified capacity as


capacity) length.

Important methods of StringBuffer class

Modifier Method Description


and Type

public append(String s) It is used to append the specified string with this


synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, It is used to insert the specified string with this
synchronized String s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int It is used to replace the string from specified
synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex, String
str)

public delete(int It is used to delete the string from specified


synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.

public char charAt(int index) It is used to return the character at the specified
position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

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

What is a mutable String?


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

1) StringBuffer Class append() Method

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

StringBufferExample.java
1565. class StringBufferExample{
1566. public static void main(String args[]){
1567. StringBuffer sb=new StringBuffer("Hello ");
1568. sb.append("Java");//now original string is changed
1569. System.out.println(sb);//prints Hello Java
1570. }
1571. }

Java StringBuilder Class


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

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String It creates a String Builder with the specified string.


str)

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class

Method Description

public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

public StringBuilder It is used to insert the specified string with this string at the
insert(int offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public StringBuilder It is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)

public StringBuilder It is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)

public StringBuilder It is used to reverse the string.


reverse()

public int capacity() It is used to return the current capacity.

public void It is used to ensure the capacity at least equal to the given
ensureCapacity(int minimum.
minimumCapacity)

public char charAt(int It is used to return the character at the specified position.
index)

public int length() It is used to return the length of the string i.e. total number of
characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

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

Java StringBuilder Examples


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

1) StringBuilder append() method

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

StringBuilderExample.java
1572. class StringBuilderExample{
1573. public static void main(String args[]){
1574. StringBuilder sb=new StringBuilder("Hello ");
1575. sb.append("Java");//now original string is changed
1576. System.out.println(sb);//prints Hello Java
1577. }
1578. }

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

N String StringBuffer
o
.

1 The String class is immutable. The StringBuffer class is


) mutable.

2 String is slow and consumes more memory when StringBuffer is fast and
) we concatenate too many strings because every consumes less memory when we
time it creates new instance. concatenate t strings.

3 String class overrides the equals() method of StringBuffer class doesn't


) Object class. So you can compare the contents of override the equals() method of
two strings by equals() method. Object class.

4 String class is slower while performing StringBuffer class is faster while


) concatenation operation. performing concatenation
operation.

5 String class uses String constant pool. StringBuffer uses Heap memory
)
Performance Test of String and StringBuffer

Difference between StringBuffer and


StringBuilder
Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder.
The StringBuilder class is introduced since JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:


N StringBuffer StringBuilder
o
.

1 StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e. not


) safe. It means two threads can't call the thread safe. It means two threads can call
methods of StringBuffer simultaneously. the methods of StringBuilder
simultaneously.

2 StringBuffer is less efficient than StringBuilder is more efficient than


) StringBuilder. StringBuffer.

3 StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
)

StringBuffer Example
BufferTest.java

1579. //Java Program to demonstrate the use of StringBuffer class.


1580. public class BufferTest{
1581. public static void main(String[] args){
1582. StringBuffer buffer=new StringBuffer("hello");
1583. buffer.append("java");
1584. System.out.println(buffer);
1585. }
1586. }

Java toString() Method


If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the String representation of the object.

If you print any object, Java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an
object etc. depending on your implementation.

Advantage of Java toString() method

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

Understanding problem without toString() method

Let's see the simple code that prints reference.

Student.java

1587. class Student{


1588. int rollno;
1589. String name;
1590. String city;
1591.
1592. Student(int rollno, String name, String city){
1593. this.rollno=rollno;
1594. this.name=name;
1595. this.city=city;
1596. }
1597.
1598. public static void main(String args[]){
1599. Student s1=new Student(101,"Raj","lucknow");
1600. Student s2=new Student(102,"Vijay","ghaziabad");
1601.
1602. System.out.println(s1);//compiler writes here s1.toString()
1603. System.out.println(s2);//compiler writes here s2.toString()
1604. }
1605. }

Exception Handling in Java


• Exception Handling
• Advantage of Exception Handling
• Hierarchy of Exception classes
• Types of Exception
• Exception Example
• Scenarios where an exception may occur

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.

Backward Skip 10sPlay VideoForward Skip 10s

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:

1606. statement 1;
1607. statement 2;
1608. statement 3;
1609. statement 4;
1610. statement 5;//exception occurs
1611. statement 6;
1612. statement 7;
1613. statement 8;
1614. statement 9;
1615. 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.

Do You Know?
• What is the difference between checked and unchecked exceptions?
• What happens behind the code int data=50/0;?
• Why use multiple catch block?
• Is there any possibility when the finally block is not executed?
• What is exception propagation?
• What is the difference between the throw and throws keyword?
• What are the 4 rules for using exception handling with method overriding?

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:

1616. Checked Exception


1617. Unchecked Exception
1618. 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 are OutOfMemoryError,


VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyw Description
ord

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

1619. public class JavaExceptionExample{


1620. public static void main(String args[]){
1621. try{
1622. //code that may raise exception
1623. int data=100/0;
1624. }catch(ArithmeticException e){System.out.println(e);}
1625. //rest code of the program
1626. System.out.println("rest of the code...");
1627. }
1628. }
Test it Now

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

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.

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

1630. String s=null;


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

1632. String s="abc";


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

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


1635. a[10]=50; //ArrayIndexOutOfBoundsException
ADVERTISEMENT

Java Exceptions Index


1636. Java Try-Catch Block
1637. Java Multiple Catch Block
1638. Java Nested Try
1639. Java Finally Block
1640. Java Throw Keyword
1641. Java Exception Propagation
1642. Java Throws Keyword
1643. Java Throw vs Throws
1644. Java Final vs Finally vs Finalize
1645. Java Exception Handling with Method Overriding
1646. Java Custom Exceptions

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

1647. try{
1648. //code that may throw an exception
1649. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1650. try{
1651. //code that may throw an exception
1652. }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.
ADVERTISEMENT

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:

• Prints out exception description.


• Prints the stack trace (Hierarchy of methods where the exception occurred).
• 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

1653. public class TryCatchExample1 {


1654.
1655. public static void main(String[] args) {
1656.
1657. int data=50/0; //may throw exception
1658.
1659. System.out.println("rest of the code");
1660.
1661. }
1662.
1663. }
Test it Now

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

1664. public class TryCatchExample2 {


1665.
1666. public static void main(String[] args) {
1667. try
1668. {
1669. int data=50/0; //may throw exception
1670. }
1671. //handling the exception
1672. catch(ArithmeticException e)
1673. {
1674. System.out.println(e);
1675. }
1676. System.out.println("rest of the code");
1677. }
1678.
1679. }

Java Catch Multiple Exceptions


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

• At a time only one exception occurs and at a time only one catch block is executed.
• 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

1680. public class MultipleCatchBlock1 {


1681.
1682. public static void main(String[] args) {
1683.
1684. try{
1685. int a[]=new int[5];
1686. a[5]=30/0;
1687. }
1688. catch(ArithmeticException e)
1689. {
1690. System.out.println("Arithmetic Exception occurs");
1691. }
1692. catch(ArrayIndexOutOfBoundsException e)
1693. {
1694. System.out.println("ArrayIndexOutOfBounds Exception occurs");
1695. }
1696. catch(Exception e)
1697. {
1698. System.out.println("Parent Exception occurs");
1699. }
1700. System.out.println("rest of the code");
1701. }
1702. }

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:

1703. ....
1704. //main try block
1705. try
1706. {
1707. statement 1;
1708. statement 2;
1709. //try catch block within another try block
1710. try
1711. {
1712. statement 3;
1713. statement 4;
1714. //try catch block within nested try block
1715. try
1716. {
1717. statement 5;
1718. statement 6;
1719. }
1720. catch(Exception e2)
1721. {
1722. //exception message
1723. }
1724.
1725. }
1726. catch(Exception e1)
1727. {
1728. //exception message
1729. }
1730. }
1731. //catch block of parent (outer) try block
1732. catch(Exception e3)
1733. {
1734. //exception message
1735. }
1736. ....

Java finally block


Java finally block is a block used to execute important code such as closing the connection,
etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.


Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if
any).

Why use Java finally block?


• finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
• The important statements to be printed can be placed in the finally block.

Usage of Java finally


Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.

TestFinallyBlock.java

1737. class TestFinallyBlock {


1738. public static void main(String args[]){
1739. try{
1740. //below code do not throw any exception
1741. int data=25/5;
1742. System.out.println(data);
1743. }
1744. //catch won't be executed
1745. catch(NullPointerException e){
1746. System.out.println(e);
1747. }
1748. //executed regardless of exception occurred or not
1749. finally {
1750. System.out.println("finally block is always executed");
1751. }
1752.
1753. System.out.println("rest of phe code...");
1754. }
1755. }

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

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

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

Let's see the example of throw IOException.

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

1758. public class TestThrow1 {


1759. //function to check if person is eligible to vote or not
1760. public static void validate(int age) {
1761. if(age<18) {
1762. //throw Arithmetic exception if not eligible to vote
1763. throw new ArithmeticException("Person is not eligible to vote");
1764. }
1765. else {
1766. System.out.println("Person is eligible to vote!!");
1767. }
1768. }
1769. //main method
1770. public static void main(String args[]){
1771. //calling the function
1772. validate(13);
1773. System.out.println("rest of the code...");
1774. }
1775. }

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.
Example 2: Throwing Checked Exception

Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked
exception is everything else under the Throwable class.

TestThrow2.java

1776. import java.io.*;


1777.
1778. public class TestThrow2 {
1779.
1780. //function to check if person is eligible to vote or not
1781. public static void method() throws FileNotFoundException {
1782.
1783. FileReader file = new
FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
1784. BufferedReader fileInput = new BufferedReader(file);
1785.
1786.
1787. throw new FileNotFoundException();
1788.
1789. }
1790. //main method
1791. public static void main(String args[]){
1792. try
1793. {
1794. method();
1795. }
1796. catch (FileNotFoundException e)
1797. {
1798. e.printStackTrace();
1799. }
1800. System.out.println("rest of the code...");
1801. }
1802. }
Output:

Example 3: Throwing User-defined Exception

exception is everything else under the Throwable class.

TestThrow3.java

1803. // class represents user-defined exception


1804. class UserDefinedException extends Exception
1805. {
1806. public UserDefinedException(String str)
1807. {
1808. // Calling constructor of parent Exception
1809. super(str);
1810. }
1811. }
1812. // Class that uses above MyException
1813. public class TestThrow3
1814. {
1815. public static void main(String args[])
1816. {
1817. try
1818. {
1819. // throw an object of user defined exception
1820. throw new UserDefinedException("This is user-defined exception");
1821. }
1822. catch (UserDefinedException ude)
1823. {
1824. System.out.println("Caught the exception");
1825. // Print the message from MyException object
1826. System.out.println(ude.getMessage());
1827. }
1828. }
1829. }

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to
provide the exception handling code so that the normal flow of the program can be
maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.

Syntax of Java throws

1830. return_type method_name() throws exception_class_name{


1831. //method code
1832. }

Which exception should be declared?

Ans: Checked exception only, because:


ADVERTISEMENT
ADVERTISEMENT

• unchecked exception: under our control so we can correct our code.


• error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

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


ADVERTISEMENT

It provides information to the caller of the method about the exception.


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

Testthrows1.java

1833. import java.io.IOException;


1834. class Testthrows1{
1835. void m()throws IOException{
1836. throw new IOException("device error");//checked exception
1837. }
1838. void n()throws IOException{
1839. m();
1840. }
1841. void p(){
1842. try{
1843. n();
1844. }catch(Exception e){System.out.println("exception handled");}
1845. }
1846. public static void main(String args[]){
1847. Testthrows1 obj=new Testthrows1();
1848. obj.p();
1849. System.out.println("normal flow...");
1850. }
1851. }
Test it Now

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.

There are two cases:


1852. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
1853. Case 2: We have declared the exception i.e. specified throws keyword with the
method.

Case 1: Handle Exception Using try-catch block

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

Testthrows2.java

1854. import java.io.*;


1855. class M{
1856. void method()throws IOException{
1857. throw new IOException("device error");
1858. }
1859. }
1860. public class Testthrows2{
1861. public static void main(String args[]){
1862. try{
1863. M m=new M();
1864. m.method();
1865. }catch(Exception e){System.out.println("exception handled");}
1866.
1867. System.out.println("normal flow...");
1868. }
1869. }

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw
the exception explicitly from a method or a block of code whereas the throws keyword is
used in signature of the method.

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
S Basis of Differences throw throws
r
.
n
o
.

1. Definition Java throw keyword is Java throws keyword is


used throw an exception used in the method
explicitly in the code, signature to declare an
inside the function or the exception which might be
block of code. thrown by the function
while the execution of the
code.

2. Type of exception Using Using throws keyword,


throw keyword, we can only we can declare both
propagate unchecked checked and unchecked
exception i.e., the checked exceptions. However, the
exception cannot be throws keyword can be
propagated using throw used to propagate
only. checked exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance followed by class names of
of Exception to be Exceptions to be thrown.
thrown.

4. Declaration throw is used within the throws is used with the


method. method signature.

5. Internal implementation We are allowed to throw We can declare multiple


only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be
multiple exceptions. thrown by the method. For
example, main() throws
IOException,
SQLException.
Java throw Example
TestThrow.java

1870. public class TestThrow {


1871. //defining a method
1872. public static void checkNum(int num) {
1873. if (num < 1) {
1874. throw new ArithmeticException("\nNumber is negative, cannot
calculate square");
1875. }
1876. else {
1877. System.out.println("Square of " + num + " is " + (num*num));
1878. }
1879. }
1880. //main method
1881. public static void main(String[] args) {
1882. TestThrow obj = new TestThrow();
1883. obj.checkNum(-3);
1884. System.out.println("Rest of the code..");
1885. }
1886. }

Output:

Backward Skip 10sPlay VideoForward Skip 10s


ADVERTISEMENT

Java throws Example


TestThrows.java

1887. public class TestThrows {


1888. //defining a method
1889. public static int divideNum(int m, int n) throws ArithmeticException {
1890. int div = m / n;
1891. return div;
1892. }
1893. //main method
1894. public static void main(String[] args) {
1895. TestThrows obj = new TestThrows();
1896. try {
1897. System.out.println(obj.divideNum(45, 0));
1898. }
1899. catch (ArithmeticException e){
1900. System.out.println("\nNumber cannot be divided by 0");
1901. }
1902.
1903. System.out.println("Rest of the code..");
1904. }
1905. }

Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception handling. Each
of these keywords has a different functionality. The basic difference between final, finally
and finalize is that the final is an access modifier, finally is the block in Exception Handling
and finalize is the method of object class.

Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

S Key final finally finalize


r
.
n
o
.
1. Definition final is the keyword finally is the block in finalize is the method
and access modifier Java Exception in Java which is used to
which is used to Handling to execute perform clean up
apply restrictions on the important code processing just before
a class, method or whether the exception object is garbage
variable. occurs or not. collected.

2. Applicabl Final keyword is Finally block is always finalize() method is


e to used with the classes, related to the try and used with the objects.
methods and catch block in
variables. exception handling.

3. Functiona (1) Once declared, (1) finally block runs finalize method
lity final variable the important code performs the cleaning
becomes constant even if exception activities with respect
and cannot be occurs or not. to the object before its
modified. (2) finally block cleans destruction.
(2) final method up all the resources
cannot be overridden used in try block
by sub class.
(3) final class cannot
be inherited.

4. Execution Final method is Finally block is finalize method is


executed only when executed as soon as executed just before
we call it. the try-catch block is the object is destroyed.
executed.

It's execution is not


dependant on the
exception.

Java final Example


Let's consider the following example where we declare final variable age. Once declared it
cannot be modified.
Exception Handling with Method Overriding in
Java
There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:


ADVERTISEMENT
ADVERTISEMENT

• If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
• If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare
parent exception.

If the superclass method does not declare an exception

Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception.

Let's consider following example based on the above rule.

TestExceptionChild.java

1906. import java.io.*;


1907. class Parent{
1908.
1909. // defining the method
1910. void msg() {
1911. System.out.println("parent method");
1912. }
1913. }
1914.
1915. public class TestExceptionChild extends Parent{
1916.
1917. // overriding the method in child class
1918. // gives compile time error
1919. void msg() throws IOException {
1920. System.out.println("TestExceptionChild");
1921. }
1922.
1923. public static void main(String args[]) {
1924. Parent p = new TestExceptionChild();
1925. p.msg();
1926. }
1927. }

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

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:


ADVERTISEMENT
ADVERTISEMENT

• To catch and provide specific treatment to a subset of existing Java exceptions.


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

1928. public class WrongFileNameException extends Exception {


1929. public WrongFileNameException(String errorMessage) {
1930. super(errorMessage);
1931. }
1932. }

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

1933. // class representing custom exception


1934. class InvalidAgeException extends Exception
1935. {
1936. public InvalidAgeException (String str)
1937. {
1938. // calling the constructor of parent Exception
1939. super(str);
1940. }
1941. }
1942.
1943. // class that uses custom exception InvalidAgeException
1944. public class TestCustomException1
1945. {
1946.
1947. // method to check the age
1948. static void validate (int age) throws InvalidAgeException{
1949. if(age < 18){
1950.
1951. // throw an object of user defined exception
1952. throw new InvalidAgeException("age is not valid to vote");
1953. }
1954. else {
1955. System.out.println("welcome to vote");
1956. }
1957. }
1958.
1959. // main method
1960. public static void main(String args[])
1961. {
1962. try
1963. {
1964. // calling the method
1965. validate(13);
1966. }
1967. catch (InvalidAgeException ex)
1968. {
1969. System.out.println("Caught the exception");
1970.
1971. // printing the message from InvalidAgeException object
1972. System.out.println("Exception occured: " + ex);
1973. }
1974.
1975. System.out.println("rest of the code...");
1976. }
1977. }
Java Inner Classes (Nested Classes)
• Java Inner classes
• Advantage of Inner class
• Difference between nested class and inner class
• Types of Nested classes

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data members
and methods.

Syntax of Inner class

1978. class Java_Outer_class{


1979. //code
1980. class Java_Inner_class{
1981. //code
1982. }
1983. }

Advantage of Java inner classes


There are three advantages of inner classes in Java. They are as follows:

Backward Skip 10sPlay VideoForward Skip 10s


ADVERTISEMENT

1984. Nested classes represent a particular type of relationship that is it can access
all the members (data members and methods) of the outer class, including
private.
1985. Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
1986. Code Optimization: It requires less code to write.
Need of Java Inner class
Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that class inside
the outer class. That way all the outer class can access all the objects of the inner class.

Do You Know
• What is the internal code generated by the compiler for member inner class?
• What are the two ways to create an anonymous inner class?
• Can we access the non-final local variable inside the local inner class?
• How to access the static nested class?
• Can we define an interface within the class?
• Can we define a class within the interface?

Difference between nested class and inner class in Java


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

Types of Nested classes


There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.
ADVERTISEMENT
ADVERTISEMENT

• Non-static nested class (inner class)


a. Member inner class
b. Anonymous inner class
c. Local inner class
• Static nested class

Type Description

Member Inner A class created within class and outside method.


Class
Anonymous A class created for implementing an interface or extending class. The
Inner Class java compiler decides its name.

Local Inner A class was created within the method.


Class

Static Nested A static class was created within the class.


Class

Nested Interface An interface created within class or interface.

Next TopicMember Inner class

Java Anonymous inner class


Java anonymous inner class is an inner class without a name and for which only a single
object is created. An anonymous inner class can be useful when making an instance of an
object with certain "extras" such as overloading methods of a class or interface, without
having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:

1987. Class (may be abstract or concrete).


1988. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

1989. abstract class Person{


1990. abstract void eat();
1991. }
1992. class TestAnonymousInner{
1993. public static void main(String args[]){
1994. Person p=new Person(){
1995. void eat(){System.out.println("nice fruits");}
1996. };
1997. p.eat();
1998. }
1999. }

Java Local inner class


A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block. Generally, this block is a method body.
Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member
of any enclosing classes. They belong to the block they are defined within, due to which local
inner classes cannot have any access modifiers associated with them. However, they can be
marked as final or abstract. These classes have access to the fields of the class enclosing it.

If you want to invoke the methods of the local inner class, you must instantiate this class
inside the method.

Java local inner class example

LocalInner1.java

2000. public class localInner1{


2001. private int data=30;//instance variable
2002. void display(){
2003. class Local{
2004. void msg(){System.out.println(data);}
2005. }
2006. Local l=new Local();
2007. l.msg();
2008. }
2009. public static void main(String args[]){
2010. localInner1 obj=new localInner1();
2011. obj.display();
2012. }
2013. }
Java static nested class
A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.
ADVERTISEMENT
ADVERTISEMENT

• It can access static data members of the outer class, including private.
• The static nested class cannot access non-static (instance) data members or

Java static nested class example with instance method


TestOuter1.java

2014. class TestOuter1{


2015. static int data=30;
2016. static class Inner{
2017. void msg(){System.out.println("data is "+data);}
2018. }
2019. public static void main(String args[]){
2020. TestOuter1.Inner obj=new TestOuter1.Inner();
2021. obj.msg();
2022. }
2023. }

Java Nested Interface


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

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.
ADVERTISEMENT
ADVERTISEMENT
• The nested interface must be public if it is declared inside the interface, but it can have
any access modifier if declared within the class.
• Nested interfaces are declared static

Syntax of nested interface which is declared within the interface

2024. interface interface_name{


2025. ...
2026. interface nested_interface_name{
2027. ...
2028. }
2029. }

Syntax of nested interface which is declared within the class

2030. class class_name{


2031. ...
2032. interface nested_interface_name{
2033. ...
2034. }
2035. }

Multithreading in Java
• Multithreading
• Multitasking
• Process-based multitasking
• Thread-based multitasking
• What is Thread

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.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:

• Process-based Multitasking (Multiprocessing)


• Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

• Each process has an address in memory. In other words, each process allocates a
separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

• Threads share the same address space.


• A thread is lightweight.
• Cost of communication between the thread is low.
Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

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

Java Thread class


Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

Java Thread Methods

S Modifier and Type Method Descriptio


. n
N
.

1) void start() It is used to


start the
execution of
the thread.

2) void run() It is used to


do an action
for a thread.

3) static void sleep() It sleeps a


thread for
the specified
amount of
time.

4) static Thread currentThread() It returns a


reference to
the
currently
executing
thread
object.

5) void join() It waits for a


thread to
die.
6) int getPriority() It returns
the priority
of the
thread.

7) void setPriority() It changes


the priority
of the
thread.

8) String getName() It returns


the name of
the thread.

9) void setName() It changes


the name of
the thread.

10 long getId() It returns


) the id of the
thread.

11 boolean isAlive() It tests if the


) thread is
alive.

12 static void yield() It causes the


) currently
executing
thread
object to
pause and
allow other
threads to
execute
temporarily.

13 void suspend() It is used to


) suspend the
thread.

14 void resume() It is used to


) resume the
suspended
thread.

15 void stop() It is used to


) stop the
thread.

16 void destroy() It is used to


) destroy the
thread
group and
all of its
subgroups.

17 boolean isDaemon() It tests if the


) thread is a
daemon
thread.

18 void setDaemon() It marks the


) thread as
daemon or
user thread.

19 void interrupt() It interrupts


) the thread.

20 boolean isinterrupted() It tests


) whether the
thread has
been
interrupted.

21 static boolean interrupted() It tests


) whether the
current
thread has
been
interrupted.

22 static int activeCount() It returns


) the number
of active
threads in
the current
thread's
thread
group.

23 void checkAccess() It
) determines
if the
currently
running
thread has
permission
to modify
the thread.

24 static boolean holdLock() It returns


) true if and
only if the
current
thread holds
the monitor
lock on the
specified
object.

25 static void dumpStack() It is used to


) print a stack
trace of the
current
thread to the
standard
error
stream.

26 StackTraceElement[] getStackTrace() It returns an


) array of
stack trace
elements
representin
g the stack
dump of the
thread.

27 static int enumerate() It is used to


) copy every
active
thread's
thread
group and
its subgroup
into the
specified
array.

28 Thread.State getState() It is used to


) return the
state of the
thread.

29 ThreadGroup getThreadGroup() It is used to


) return the
thread
group to
which this
thread
belongs

30 String toString() It is used to


) return a
string
representati
on of this
thread,
including
the thread's
name,
priority, and
thread
group.

31 void notify() It is used to


) give the
notification
for only one
thread
which is
waiting for a
particular
object.

32 void notifyAll() It is used to


) give the
notification
to all waiting
threads of a
particular
object.

33 void setContextClassLoader() It sets the


) context
ClassLoader
for the
Thread.

34 ClassLoader getContextClassLoader() It returns


) the context
ClassLoader
for the
thread.

35 static getDefaultUncaughtExceptionHand It returns


) Thread.UncaughtExceptionHa ler() the default
ndler handler
invoked
when a
thread
abruptly
terminates
due to an
uncaught
exception.

36 static void setDefaultUncaughtExceptionHand It sets the


) ler() default
handler
invoked
when a
thread
abruptly
terminates
due to an
uncaught
exception.

Do You Know
• How to perform two tasks by two threads?
• How to perform multithreading by anonymous class?
• What is the Thread Scheduler and what is the difference between preemptive
scheduling and time slicing?
• What happens if we start a thread twice?
• What happens if we call the run() method instead of start() method?
• What is the purpose of join method?
• Why JVM terminates the daemon thread if no user threads are remaining?
• What is the shutdown hook?
• What is garbage collection?
• What is the purpose of finalize() method?
• What does the gc() method?
• What is synchronization and why use synchronization?
• What is the difference between synchronized method and synchronized block?
• What are the two ways to perform static synchronization?
• What is deadlock and when it can occur?
• What is interthread-communication or cooperation?
What will we learn in Multithreading
• Multithreading
• Life Cycle of a Thread
• Two ways to create a Thread
• How to perform multiple tasks by multiple threads
• Thread Scheduler
• Sleeping a thread
• Can we start a thread twice?
• What happens if we call the run() method instead of start() method?
• Joining a thread
• Naming a thread
• Priority of a thread
• Daemon Thread
• ShutdownHook
• Garbage collection
• Synchronization with synchronized method
• Synchronized block
• Static synchronization
• Deadlock
• Inter-thread communication

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

2036. New
2037. Active
2038. Blocked / Waiting
2039. Timed Waiting
2040. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other is
running.
ADVERTISEMENT
ADVERTISEMENT

• Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant
of time. It is the duty of the thread scheduler to provide the thread time to run, i.e.,
moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other
thread, so that the other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state. In the runnable state, there is a queue where the threads lie.
• Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
ADVERTISEMENT

For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to
print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread
A is in the blocked state. A thread in the blocked state is unable to perform any execution and
thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that
thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting
or blocked state.

When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state. The main thread then waits for the child threads to complete their tasks. When
the child threads complete their job, a notification is sent to the main thread, which again
moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen
thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread
lies in the waiting state for a specific span of time, and not forever. A real example of timed
waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts
the thread in the timed wait state. After the time runs out, the thread wakes up and start its
execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:

• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the thread
is dead, and there is no way one can respawn (active after kill) the dead thread.
ADVERTISEMENT
ADVERTISEMENT

The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States


In Java, one can get the current state of a thread using the Thread.getState() method. The
java.lang.Thread.State class of Java provides the constants ENUM to represent the state of
a thread. These constants are:

2041. public static final Thread.State NEW

It represents the first state of a thread that is the NEW state.

2042. public static final Thread.State RUNNABLE

It represents the runnable state.It means a thread is waiting in the queue to run.

2043. public static final Thread.State BLOCKED

It represents the blocked state. In this state, the thread is waiting to acquire a lock.
2044. public static final Thread.State WAITING

It represents the waiting state. A thread will go to this state when it invokes the Object.wait()
method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for
another thread to complete its task.

2045. public static final Thread.State TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the
time constraint. A thread invoking the following method reaches the timed waiting state.
ADVERTISEMENT

• sleep
• join with timeout
• wait with timeout
• parkUntil
• parkNanos
2046. public static final Thread.State TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated thread means
it has completed its execution.

Java Program for Demonstrating Thread States


The following Java program shows some of the states of a thread defined above.

FileName: ThreadState.java

2047. // ABC class implements the interface Runnable


2048. class ABC implements Runnable
2049. {
2050. public void run()
2051. {
2052.
2053. // try-catch block
2054. try
2055. {
2056. // moving thread t2 to the state timed waiting
2057. Thread.sleep(100);
2058. }
2059. catch (InterruptedException ie)
2060. {
2061. ie.printStackTrace();
2062. }
2063.
2064.
2065. System.out.println("The state of thread t1 while it invoked the method join()
on thread t2 -"+ ThreadState.t1.getState());
2066.
2067. // try-catch block
2068. try
2069. {
2070. Thread.sleep(200);
2071. }
2072. catch (InterruptedException ie)
2073. {
2074. ie.printStackTrace();
2075. }
2076. }
2077. }
2078.
2079. // ThreadState class implements the interface Runnable
2080. public class ThreadState implements Runnable
2081. {
2082. public static Thread t1;
2083. public static ThreadState obj;
2084.
2085. // main method
2086. public static void main(String argvs[])
2087. {
2088. // creating an object of the class ThreadState
2089. obj = new ThreadState();
2090. t1 = new Thread(obj);
2091.
2092. // thread t1 is spawned
2093. // The thread t1 is currently in the NEW state.
2094. System.out.println("The state of thread t1 after spawning it - " + t1.getState());
2095.
2096. // invoking the start() method on
2097. // the thread t1
2098. t1.start();
2099.
2100. // thread t1 is moved to the Runnable state
2101. System.out.println("The state of thread t1 after invoking the method start() on
it - " + t1.getState());
2102. }
2103.
2104. public void run()
2105. {
2106. ABC myObj = new ABC();
2107. Thread t2 = new Thread(myObj);
2108.
2109. // thread t2 is created and is currently in the NEW state.
2110. System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
2111. t2.start();
2112.
2113. // thread t2 is moved to the runnable state
2114. System.out.println("the state of thread t2 after calling the method start() on it
- " + t2.getState());
2115.
2116. // try-catch block for the smooth flow of the program
2117. try
2118. {
2119. // moving the thread t1 to the state timed waiting
2120. Thread.sleep(200);
2121. }
2122. catch (InterruptedException ie)
2123. {
2124. ie.printStackTrace();
2125. }
2126.
2127. System.out.println("The state of thread t2 after invoking the method sleep()
on it - "+ t2.getState() );
2128.
2129. // try-catch block for the smooth flow of the program
2130. try
2131. {
2132. // waiting for thread t2 to complete its execution
2133. t2.join();
2134. }
2135. catch (InterruptedException ie)
2136. {
2137. ie.printStackTrace();
2138. }
2139. System.out.println("The state of thread t2 when it has completed it's execution
- " + t2.getState());
2140. }
2141.
2142. }

Output:

The state of thread t1 after spawning it - NEW


The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2
-TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it -
TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED
Explanation: Whenever we spawn a new thread, that thread attains the new state. When
the method start() is invoked on a thread, the thread scheduler moves that thread to the
runnable state. Whenever the join() method is invoked on any thread instance, the current
thread executing that statement has to wait for this thread to finish its execution, i.e., move
that thread to the terminated state. Therefore, before the final print statement is printed on
the console, the program invokes the method join() on thread t2, making the thread t1 wait
while the thread t2 finishes its execution and thus, the thread t2 get to the terminated or
dead state. Thread t1 goes to the waiting state because it is waiting for thread t2 to finish it's
execution as it has invoked the method join() on thread t2.

Java Threads | How to create a thread in Java


There are two ways to create a thread:

2143. By extending Thread class


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


ADVERTISEMENT

• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)

Commonly used methods of Thread class:

2145. public void run(): is used to perform action for a thread.


2146. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
2147. public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of milliseconds.
2148. public void join(): waits for a thread to die.
2149. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
2150. public int getPriority(): returns the priority of the thread.
2151. public int setPriority(int priority): changes the priority of the thread.
2152. public String getName(): returns the name of the thread.
2153. public void setName(String name): changes the name of the thread.
2154. public Thread currentThread(): returns the reference of currently
executing thread.
2155. public int getId(): returns the id of the thread.
2156. public Thread.State getState(): returns the state of the thread.
2157. public boolean isAlive(): tests if the thread is alive.
2158. public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
2159. public void suspend(): is used to suspend the thread(depricated).
2160. public void resume(): is used to resume the suspended thread(depricated).
2161. public void stop(): is used to stop the thread(depricated).
2162. public boolean isDaemon(): tests if the thread is a daemon thread.
2163. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
2164. public void interrupt(): interrupts the thread.
2165. public boolean isInterrupted(): tests if the thread has been interrupted.
2166. public static boolean interrupted(): tests if the current thread has been
interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().

2167. 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:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

2168. class Multi extends Thread{


2169. public void run(){
2170. System.out.println("thread is running...");
2171. }
2172. public static void main(String args[]){
2173. Multi t1=new Multi();
2174. t1.start();
2175. }
2176. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

2177. class Multi3 implements Runnable{


2178. public void run(){
2179. System.out.println("thread is running...");
2180. }
2181.
2182. public static void main(String args[]){
2183. Multi3 m1=new Multi3();
2184. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
2185. t1.start();
2186. }
2187. }

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.

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

2188. public class MyThread1


2189. {
2190. // Main method
2191. public static void main(String argvs[])
2192. {
2193. // creating an object of the Thread class using the constructor Thread(String
name)
2194. Thread t= new Thread("My first thread");
2195.
2196. // the start() method moves the thread to the active state
2197. t.start();
2198. // getting the thread name by invoking the getName() method
2199. String str = t.getName();
2200. System.out.println(str);
2201. }
2202. }

Output:

My first thread
4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

2203. public class MyThread2 implements Runnable


2204. {
2205. public void run()
2206. {
2207. System.out.println("Now the thread is running ...");
2208. }
2209.
2210. // main method
2211. public static void main(String argvs[])
2212. {
2213. // creating an object of the class MyThread2
2214. Runnable r1 = new MyThread2();
2215.
2216. // creating an object of the class Thread using Thread(Runnable r, String
name)
2217. Thread th1 = new Thread(r1, "My new thread");
2218.
2219. // the start() method moves the thread to the active state
2220. th1.start();
2221.
2222. // getting the thread name by invoking the getName() method
2223. String str = th1.getName();
2224. System.out.println(str);
2225. }
2226. }

Thread Scheduler in Java


A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it
is in the runnable state. However, if there is more than one thread in the runnable state, it is
up to the thread scheduler to pick one of the threads and ignore the other ones. There are
some criteria that decide which thread will execute first. There are two factors for scheduling
a thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it
means that thread has got a better chance of getting picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state, then
priority cannot be the factor to pick a thread from these two threads. In such a case, arrival
time of thread is considered by the thread scheduler. A thread that arrived first gets the
preference over the other threads.

Thread Scheduler Algorithms


On the basis of the above-mentioned factors, the scheduling algorithm is followed by a Java
thread scheduler.

First Come First Serve Scheduling:

In this scheduling algorithm, the scheduler picks the threads thar arrive first in the runnable
queue. Observe the following table:

Threads Time of Arrival

t1 0

t2 1

t3 2

t4 3

In the above table, we can see that Thread t1 has arrived first, then Thread t2, then t3, and at
last t4, and the order in which the threads will be processed is according to the time of arrival
of threads.
Hence, Thread t1 will be processed first, and Thread t4 will be processed last.

Time-slicing scheduling:

Usually, the First Come First Serve algorithm is non-preemptive, which is bad as it may lead
to infinite blocking (also known as starvation). To avoid that, some time-slices are provided
to the threads so that after some time, the running thread has to give up the CPU. Thus, the
other waiting threads also get time to run their job.

In the above diagram, each thread is given a time slice of 2 seconds. Thus, after 2 seconds,
the first thread leaves the CPU, and the CPU is then captured by Thread2. The same process
repeats for the other threads too.

Preemptive-Priority Scheduling:

The name of the scheduling algorithm denotes that the algorithm is related to the priority of
the threads.
Suppose there are multiple threads available in the runnable state. The thread scheduler
picks that thread that has the highest priority. Since the algorithm is also preemptive,
therefore, time slices are also provided to the threads to avoid starvation. Thus, after some
time, even if the highest priority thread has not completed its job, it has to release the CPU
because of preemption.

Working of the Java Thread Scheduler


Let's understand the working of the Java thread scheduler. Suppose, there are five threads
that have different arrival times and different priorities. Now, it is the responsibility of the
thread scheduler to decide which thread will get the CPU first.

The thread scheduler selects the thread that has the highest priority, and the thread begins
the execution of the job. If a thread is already in runnable state and another thread (that has
higher priority) reaches in the runnable state, then the current thread is pre-empted from
the processor, and the arrived thread with higher priority gets the CPU time.

When two threads (Thread 2 and Thread 3) having the same priorities and arrival time, the
scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that arrives first
gets the opportunity to execute first.

Thread.sleep() in Java with Examples


The Java Thread class provides the two variant of the sleep() method. First one accepts only
an arguments, whereas the other variant accepts two arguments. The method sleep() is
being used to halt the working of a thread for a given amount of time. The time up to which
the thread remains in the sleeping state is known as the sleeping time of the thread. After the
sleeping time is over, the thread starts its execution from where it has left.

The sleep() Method Syntax:

Following are the syntax of the sleep() method.

2227. public static void sleep(long mls) throws InterruptedException


2228. public static void sleep(long mls, int n) throws InterruptedException

The method sleep() with the one parameter is the native method, and the implementation of
the native method is accomplished in another programming language. The other methods
having the two parameters are not the native method. That is, its implementation is
accomplished in Java. We can access the sleep() methods with the help of the Thread class,
as the signature of the sleep() methods contain the static keyword. The native, as well as the
non-native method, throw a checked Exception. Therefore, either try-catch block or the
throws keyword can work here.

The Thread.sleep() method can be used with any thread. It means any other thread or the
main thread can invoke the sleep() method.

Parameters:

The following are the parameters used in the sleep() method.


mls: The time in milliseconds is represented by the parameter mls. The duration for which
the thread will sleep is given by the method sleep().

n: It shows the additional time up to which the programmer or developer wants the thread
to be in the sleeping state. The range of n is from 0 to 999999.

The method does not return anything.

Important Points to Remember About the Sleep() Method

Whenever the Thread.sleep() methods execute, it always halts the execution of the current
thread.

Whenever another thread does interruption while the current thread is already in the sleep
mode, then the InterruptedException is thrown.

If the system that is executing the threads is busy, then the actual sleeping time of the thread
is generally more as compared to the time passed in arguments. However, if the system
executing the sleep() method has less load, then the actual sleeping time of the thread is
almost equal to the time passed in the argument.

Example of the sleep() method in Java : on the custom thread

The following example shows how one can use the sleep() method on the custom thread.

FileName: TestSleepMethod1.java

2229. class TestSleepMethod1 extends Thread{


2230. public void run(){
2231. for(int i=1;i<5;i++){
2232. // the thread will sleep for the 500 milli seconds
2233. try{Thread.sleep(500);}catch(InterruptedException
e){System.out.println(e);}
2234. System.out.println(i);
2235. }
2236. }
2237. public static void main(String args[]){
2238. TestSleepMethod1 t1=new TestSleepMethod1();
2239. TestSleepMethod1 t2=new TestSleepMethod1();
2240.
2241. t1.start();
2242. t2.start();
2243. }
2244. }

Output:

1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.

Example of the sleep() Method in Java : on the main thread

FileName: TestSleepMethod2.java

2245. // important import statements


2246. import java.lang.Thread;
2247. import java.io.*;
2248.
2249.
2250. public class TestSleepMethod2
2251. {
2252. // main method
2253. public static void main(String argvs[])
2254. {
2255.
2256. try {
2257. for (int j = 0; j < 5; j++)
2258. {
2259.
2260. // The main thread sleeps for the 1000 milliseconds, which is 1 sec
2261. // whenever the loop runs
2262. Thread.sleep(1000);
2263.
2264. // displaying the value of the variable
2265. System.out.println(j);
2266. }
2267. }
2268. catch (Exception expn)
2269. {
2270. // catching the exception
2271. System.out.println(expn);
2272. }
2273. }
2274. }

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time,
it will throw exception.

Let's understand it by the example given below:

2275. public class TestThreadTwice1 extends Thread{


2276. public void run(){
2277. System.out.println("running...");
2278. }
2279. public static void main(String args[]){
2280. TestThreadTwice1 t1=new TestThreadTwice1();
2281. t1.start();
2282. t1.start();
2283. }
2284. }
What if we call Java run() method directly instead
start() method?
ADVERTISEMENT
ADVERTISEMENT

• Each thread starts in a separate call stack.


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

FileName: TestCallRun1.java

2285. class TestCallRun1 extends Thread{


2286. public void run(){
2287. System.out.println("running...");
2288. }
2289. public static void main(String args[]){
2290. TestCallRun1 t1=new TestCallRun1();
2291. t1.run();//fine, but does not start a separate call stack
2292. }
2293. }

ava join() method


The join() method in Java is provided by the java.lang.Thread class that permits one thread
to wait until the other thread to finish its execution. Suppose th be the object the class Thread
whose thread is doing its execution currently, then the th.join(); statement ensures that th is
finished before the program does the execution of the next statement. When there are more
than one thread invoking the join() method, then it leads to overloading on the join() method
that permits the developer or programmer to mention the waiting period. However, similar
to the sleep() method in Java, the join() method is also dependent on the operating system
for the timing, so we should not assume that the join() method waits equal to the time we
mention in the parameters. The following are the three overloaded join() methods.

Description of The Overloaded join() Method


join(): When the join() method is invoked, the current thread stops its execution and the
thread goes into the wait state. The current thread remains in the wait state until the thread
on which the join() method is invoked has achieved its dead state. If interruption of the
thread occurs, then it throws the InterruptedException.
Syntax:

2294. public final void join() throws InterruptedException

join(long mls): When the join() method is invoked, the current thread stops its execution
and the thread goes into the wait state. The current thread remains in the wait state until the
thread on which the join() method is invoked called is dead or the wait for the specified time
frame(in milliseconds) is over.

Backward Skip 10sPlay VideoForward Skip 10s

Syntax:

2295. public final synchronized void join(long mls) throws


InterruptedException, where mls is in milliseconds

join(long mls, int nanos): When the join() method is invoked, the current thread stops its
execution and go into the wait state. The current thread remains in the wait state until the
thread on which the join() method is invoked called is dead or the wait for the specified time
frame(in milliseconds + nanos) is over.

Syntax:

2296. public final synchronized void join(long mls, int nanos) throws
InterruptedException, where mls is in milliseconds.

Example of join() Method in Java


The following program shows the usage of the join() method.

FileName: ThreadJoinExample.java

2297. // A Java program for understanding


2298. // the joining of threads
2299.
2300. // import statement
2301. import java.io.*;
2302.
2303. // The ThreadJoin class is the child class of the class Thread
2304. class ThreadJoin extends Thread
2305. {
2306. // overriding the run method
2307. public void run()
2308. {
2309. for (int j = 0; j < 2; j++)
2310. {
2311. try
2312. {
2313. // sleeping the thread for 300 milli seconds
2314. Thread.sleep(300);
2315. System.out.println("The current thread name is: " +
Thread.currentThread().getName());
2316. }
2317. // catch block for catching the raised exception
2318. catch(Exception e)
2319. {
2320. System.out.println("The exception has been caught: " + e);
2321. }
2322. System.out.println( j );
2323. }
2324. }
2325. }
2326.
2327. public class ThreadJoinExample
2328. {
2329. // main method
2330. public static void main (String argvs[])
2331. {
2332.
2333. // creating 3 threads
2334. ThreadJoin th1 = new ThreadJoin();
2335. ThreadJoin th2 = new ThreadJoin();
2336. ThreadJoin th3 = new ThreadJoin();
2337.
2338. // thread th1 starts
2339. th1.start();
2340.
2341. // starting the second thread after when
2342. // the first thread th1 has ended or died.
2343. try
2344. {
2345. System.out.println("The current thread name is: "+
Thread.currentThread().getName());
2346.
2347. // invoking the join() method
2348. th1.join();
2349. }
2350.
2351. // catch block for catching the raised exception
2352. catch(Exception e)
2353. {
2354. System.out.println("The exception has been caught " + e);
2355. }
2356.
2357. // thread th2 starts
2358. th2.start();
2359.
2360. // starting the th3 thread after when the thread th2 has ended or died.
2361. try
2362. {
2363. System.out.println("The current thread name is: " +
Thread.currentThread().getName());
2364. th2.join();
2365. }
2366.
2367. // catch block for catching the raised exception
2368. catch(Exception e)
2369. {
2370. System.out.println("The exception has been caught " + e);
2371. }
2372.
2373. // thread th3 starts
2374. th3.start();
2375. }
2376. }

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

Backward Skip 10sPlay VideoForward Skip 10s

3 constants defined in Thread class:


2377. public static int MIN_PRIORITY
2378. public static int NORM_PRIORITY
2379. 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: ThreadPriorityExample.java

2380. // Importing the required classes


2381. import java.lang.*;
2382.
2383. public class ThreadPriorityExample extends Thread
2384. {
2385.
2386. // Method 1
2387. // Whenever the start() method is called by a thread
2388. // the run() method is invoked
2389. public void run()
2390. {
2391. // the print statement
2392. System.out.println("Inside the run() method");
2393. }
2394.
2395. // the main method
2396. public static void main(String argvs[])
2397. {
2398. // Creating threads with the help of ThreadPriorityExample class
2399. ThreadPriorityExample th1 = new ThreadPriorityExample();
2400. ThreadPriorityExample th2 = new ThreadPriorityExample();
2401. ThreadPriorityExample th3 = new ThreadPriorityExample();
2402.
2403. // We did not mention the priority of the thread.
2404. // Therefore, the priorities of the thread is 5, the default value
2405.
2406. // 1st Thread
2407. // Displaying the priority of the thread
2408. // using the getPriority() method
2409. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
2410.
2411. // 2nd Thread
2412. // Display the priority of the thread
2413. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
2414.
2415. // 3rd Thread
2416. // // Display the priority of the thread
2417. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
2418.
2419. // Setting priorities of above threads by
2420. // passing integer arguments
2421. th1.setPriority(6);
2422. th2.setPriority(3);
2423. th3.setPriority(9);
2424.
2425. // 6
2426. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
2427.
2428. // 3
2429. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
2430.
2431. // 9
2432. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
2433.
2434. // Main thread
2435.
2436. // Displaying name of the currently executing thread
2437. System.out.println("Currently Executing The Thread : " +
Thread.currentThread().getName());
2438.
2439. System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
2440.
2441. // Priority of the main thread is 10 now
2442. Thread.currentThread().setPriority(10);
2443.
2444. System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
2445. }
2446. }

Daemon Thread in Java


Daemon thread in Java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java


ADVERTISEMENT
ADVERTISEMENT

• It provides services to user threads for background supporting tasks. It has no role in
life than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.

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

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

Java Thread Pool


Java Thread pool represents a group of worker threads that are waiting for the job and
reused many times.
In the case of a thread pool, a group of fixed-size threads is created. A thread from the thread
pool is pulled out and assigned a job by the service provider. After completion of the job, the
thread is contained in the thread pool again.

Thread Pool Methods


newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.

newCachedThreadPool(): The method creates a new thread pool that creates the new
threads when needed but will still use the previously created thread whenever they are
available to use.

Backward Skip 10sPlay VideoForward Skip 10s

newSingleThreadExecutor(): The method creates a new thread.

Advantage of Java Thread Pool

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

Real time usage

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

Example of Java Thread Pool


Let's see a simple example of the Java thread pool using ExecutorService and Executors.

How to perform single task by multiple threads in


Java?
If you have to perform a single task by many threads, have only one run() method. For
example:

Program of performing single task by multiple threads

FileName: TestMultitasking1.java

2447. class TestMultitasking1 extends Thread{


2448. public void run(){
2449. System.out.println("task one");
2450. }
2451. public static void main(String args[]){
2452. TestMultitasking1 t1=new TestMultitasking1();
2453. TestMultitasking1 t2=new TestMultitasking1();
2454. TestMultitasking1 t3=new TestMultitasking1();
2455.
2456. t1.start();
2457. t2.start();
2458. t3.start();
2459. }
2460. }

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


ADVERTISEMENT
ADVERTISEMENT

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

Java Runtime class


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

Important methods of Java Runtime class

N Method Description
o
.

1 public static Runtime getRuntime() returns the instance of Runtime


) class.

2 public void exit(int status) terminates the current virtual


) machine.

3 public void addShutdownHook(Thread hook) registers new hook thread.


)

4 public Process exec(String command)throws executes given command in a


) IOException separate process.

5 public int availableProcessors() returns no. of available processors.


)

6 public long freeMemory() returns amount of free memory in


) JVM.

7 public long totalMemory() returns amount of total memory in


) JVM.

Java Runtime exec() method


2461. public class Runtime1{
2462. public static void main(String args[])throws Exception{
2463. Runtime.getRuntime().exec("notepad");//will open a new notepad
2464. }
2465. }
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

2466. To prevent thread interference.


2467. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

2468. Process Synchronization


2469. Thread Synchronization

Here, we will discuss only thread synchronization.

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

2470. Mutual Exclusive


a. Synchronized method.
b. Synchronized block.
c. Static synchronization.
2471. 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:

2472. By Using Synchronized Method


2473. By Using Synchronized Block
2474. 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

2475. class Table{


2476. void printTable(int n){//method not synchronized
2477. for(int i=1;i<=5;i++){
2478. System.out.println(n*i);
2479. try{
2480. Thread.sleep(400);
2481. }catch(Exception e){System.out.println(e);}
2482. }
2483.
2484. }
2485. }
2486.
2487. class MyThread1 extends Thread{
2488. Table t;
2489. MyThread1(Table t){
2490. this.t=t;
2491. }
2492. public void run(){
2493. t.printTable(5);
2494. }
2495.
2496. }
2497. class MyThread2 extends Thread{
2498. Table t;
2499. MyThread2(Table t){
2500. this.t=t;
2501. }
2502. public void run(){
2503. t.printTable(100);
2504. }
2505. }
2506.
2507. class TestSynchronization1{
2508. public static void main(String args[]){
2509. Table obj = new Table();//only one object
2510. MyThread1 t1=new MyThread1(obj);
2511. MyThread2 t2=new MyThread2(obj);
2512. t1.start();
2513. t2.start();
2514. }
2515. }

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

2516. //example of java synchronized method


2517. class Table{
2518. synchronized void printTable(int n){//synchronized method
2519. for(int i=1;i<=5;i++){
2520. System.out.println(n*i);
2521. try{
2522. Thread.sleep(400);
2523. }catch(Exception e){System.out.println(e);}
2524. }
2525.
2526. }
2527. }
2528.
2529. class MyThread1 extends Thread{
2530. Table t;
2531. MyThread1(Table t){
2532. this.t=t;
2533. }
2534. public void run(){
2535. t.printTable(5);
2536. }
2537.
2538. }
2539. class MyThread2 extends Thread{
2540. Table t;
2541. MyThread2(Table t){
2542. this.t=t;
2543. }
2544. public void run(){
2545. t.printTable(100);
2546. }
2547. }
2548.
2549. public class TestSynchronization2{
2550. public static void main(String args[]){
2551. Table obj = new Table();//only one object
2552. MyThread1 t1=new MyThread1(obj);
2553. MyThread2 t2=new MyThread2(obj);
2554. t1.start();
2555. t2.start();
2556. }
2557. }

Output:
ADVERTISEMENT

5
10
15
20
25
100
200
300
400
500
Example of synchronized method by using annonymous
class
In this program, we have created the two threads by using the anonymous class, so less
coding is required.

TestSynchronization3.java

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


2559. class Table{
2560. synchronized void printTable(int n){//synchronized method
2561. for(int i=1;i<=5;i++){
2562. System.out.println(n*i);
2563. try{
2564. Thread.sleep(400);
2565. }catch(Exception e){System.out.println(e);}
2566. }
2567.
2568. }
2569. }
2570.
2571. public class TestSynchronization3{
2572. public static void main(String args[]){
2573. final Table obj = new Table();//only one object
2574.
2575. Thread t1=new Thread(){
2576. public void run(){
2577. obj.printTable(5);
2578. }
2579. };
2580. Thread t2=new Thread(){
2581. public void run(){
2582. obj.printTable(100);
2583. }
2584. };
2585.
2586. t1.start();
2587. t2.start();
2588. }
2589. }

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any specific resource of the
method.

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in
such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to Remember
ADVERTISEMENT
ADVERTISEMENT

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


• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM, to provide access control
to a shared resource.
• The system performance may degrade because of the slower working of
synchronized keyword.
• Java synchronized block is more efficient than Java synchronized method.

Syntax

2590. synchronized (object reference expression) {


2591. //code block
2592. }
Example of Synchronized Block

Let's see the simple example of synchronized block.

TestSynchronizedBlock1.java

2593. class Table


2594. {
2595. void printTable(int n){
2596. synchronized(this){//synchronized block
2597. for(int i=1;i<=5;i++){
2598. System.out.println(n*i);
2599. try{
2600. Thread.sleep(400);
2601. }catch(Exception e){System.out.println(e);}
2602. }
2603. }
2604. }//end of the method
2605. }
2606.
2607. class MyThread1 extends Thread{
2608. Table t;
2609. MyThread1(Table t){
2610. this.t=t;
2611. }
2612. public void run(){
2613. t.printTable(5);
2614. }
2615.
2616. }
2617. class MyThread2 extends Thread{
2618. Table t;
2619. MyThread2(Table t){
2620. this.t=t;
2621. }
2622. public void run(){
2623. t.printTable(100);
2624. }
2625. }
2626.
2627. public class TestSynchronizedBlock1{
2628. public static void main(String args[]){
2629. Table obj = new Table();//only one object
2630. MyThread1 t1=new MyThread1(obj);
2631. MyThread2 t2=new MyThread2(obj);
2632. t1.start();
2633. t2.start();
2634. }
2635. }

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

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

Example of Static Synchronization

In this example we have used synchronized keyword on the static method to perform static
synchronization.

TestSynchronization4.java

Backward Skip 10sPlay VideoForward Skip 10s


2636. class Table
2637. {
2638. synchronized static void printTable(int n){
2639. for(int i=1;i<=10;i++){
2640. System.out.println(n*i);
2641. try{
2642. Thread.sleep(400);
2643. }catch(Exception e){}
2644. }
2645. }
2646. }
2647. class MyThread1 extends Thread{
2648. public void run(){
2649. Table.printTable(1);
2650. }
2651. }
2652. class MyThread2 extends Thread{
2653. public void run(){
2654. Table.printTable(10);
2655. }
2656. }
2657. class MyThread3 extends Thread{
2658. public void run(){
2659. Table.printTable(100);
2660. }
2661. }
2662. class MyThread4 extends Thread{
2663. public void run(){
2664. Table.printTable(1000);
2665. }
2666. }
2667. public class TestSynchronization4{
2668. public static void main(String t[]){
2669. MyThread1 t1=new MyThread1();
2670. MyThread2 t2=new MyThread2();
2671. MyThread3 t3=new MyThread3();
2672. MyThread4 t4=new MyThread4();
2673. t1.start();
2674. t2.start();
2675. t3.start();
2676. t4.start();
2677. }
2678. }

Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting
for an object lock that is acquired by first thread. Since, both threads are waiting for each
other to release the lock, the condition is called deadlock.
Example of Deadlock in Java

TestDeadlockExample1.java

2679. public class TestDeadlockExample1 {


2680. public static void main(String[] args) {
2681. final String resource1 = "ratan jaiswal";
2682. final String resource2 = "vimal jaiswal";
2683. // t1 tries to lock resource1 then resource2
2684. Thread t1 = new Thread() {
2685. public void run() {
2686. synchronized (resource1) {
2687. System.out.println("Thread 1: locked resource 1");
2688.
2689. try { Thread.sleep(100);} catch (Exception e) {}
2690.
2691. synchronized (resource2) {
2692. System.out.println("Thread 1: locked resource 2");
2693. }
2694. }
2695. }
2696. };
2697.
2698. // t2 tries to lock resource2 then resource1
2699. Thread t2 = new Thread() {
2700. public void run() {
2701. synchronized (resource2) {
2702. System.out.println("Thread 2: locked resource 2");
2703.
2704. try { Thread.sleep(100);} catch (Exception e) {}
2705.
2706. synchronized (resource1) {
2707. System.out.println("Thread 2: locked resource 1");
2708. }
2709. }
2710. }
2711. };
2712.
2713.
2714. t1.start();
2715. t2.start();
2716. }
2717. }

nter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads
to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

• wait()
• notify()
• notifyAll()

1) wait() method

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

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount
InterruptedException 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:

2718. public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

2719. public final void notifyAll()

Understanding the process of inter-thread communication


The point to point explanation of the above diagram is as follows:

2720. Threads enter to acquire lock.


2721. Lock is acquired by on thread.
2722. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
2723. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
2724. Now thread is available to acquire lock.
2725. 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, sleep is


notifyAll() methods completed.

Example of Inter Thread Communication in Java

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

Test.java

2726. class Customer{


2727. int amount=10000;
2728.
2729. synchronized void withdraw(int amount){
2730. System.out.println("going to withdraw...");
2731.
2732. if(this.amount<amount){
2733. System.out.println("Less balance; waiting for deposit...");
2734. try{wait();}catch(Exception e){}
2735. }
2736. this.amount-=amount;
2737. System.out.println("withdraw completed...");
2738. }
2739.
2740. synchronized void deposit(int amount){
2741. System.out.println("going to deposit...");
2742. this.amount+=amount;
2743. System.out.println("deposit completed... ");
2744. notify();
2745. }
2746. }
2747.
2748. class Test{
2749. public static void main(String args[]){
2750. final Customer c=new Customer();
2751. new Thread(){
2752. public void run(){c.withdraw(15000);}
2753. }.start();
2754. new Thread(){
2755. public void run(){c.deposit(10000);}
2756. }.start();
2757.
2758. }}
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the
interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.

The 3 methods provided by the Thread class for interrupting a thread

• public void interrupt()


• public static boolean interrupted()
• public boolean isInterrupted()

Example of interrupting a thread that stops working


In this example, after interrupting the thread, we are propagating it, so it will stop working.
If we don't want to stop the thread, we can handle it where sleep() or wait() method is
invoked. Let's first see the example where we are propagating the exception.

TestInterruptingThread1.java

2759. class TestInterruptingThread1 extends Thread{


2760. public void run(){
2761. try{
2762. Thread.sleep(1000);
2763. System.out.println("task");
2764. }catch(InterruptedException e){
2765. throw new RuntimeException("Thread interrupted..."+e);
2766. }
2767.
2768. }
2769.
2770. public static void main(String args[]){
2771. TestInterruptingThread1 t1=new TestInterruptingThread1();
2772. t1.start();
2773. try{
2774. t1.interrupt();
2775. }catch(Exception e){System.out.println("Exception handled "+e);}
2776.
2777. }
2778. }

Collections in Java
• Java Collection Framework
• Hierarchy of Collection Framework
• Collection interface
• Iterator interface

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.

PauseNext
Unmute
Current Time 0:13
/
Duration 18:10
Loaded: 5.14%
Â
Fullscreen

What is a framework in Java

• It provides readymade architecture.


• It represents a set of classes and interfaces.
• It is optional.

What is Collection framework

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

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


2780. Algorithm

ADVERTISEMENT

Do You Know?
• What are the two ways to iterate the elements of a collection?
• What is the difference between ArrayList and LinkedList classes in collection
framework?
• What is the difference between ArrayList and Vector classes in collection framework?
• What is the difference between HashSet and HashMap classes in collection
framework?
• What is the difference between HashMap and Hashtable class?
• What is the difference between Iterator and Enumeration interface in collection
framework?
• How can we sort the elements of an object? What is the difference between
Comparable and Comparator interfaces?
• What does the hashcode() method?
• What is the difference between Java collection and Java collections?

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all the
classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

N Method Description
o
.

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

2 public boolean It is used to insert the specified collection


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

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


element)

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


removeAll(Collection<?> c) collection from the invoking collection.
5 default boolean It is used to delete all the elements of the
removeIf(Predicate<? super E> collection that satisfy the specified predicate.
filter)

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


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

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


collection.

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

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


element)

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


0 containsAll(Collection<?> c) collection.

1 public Iterator iterator() It returns an iterator.


1

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


2

1 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
3 type of the returned array is that of the specified
array.

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


4

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


5 parallelStream() collection as its source.

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


6 as its source.

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


7 spliterator() elements in the collection.

1 public boolean equals(Object It matches two collections.


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

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

Methods of Iterator interface

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

N Method Description
o
.

1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.

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

3 public void It removes the last elements returned by the iterator. It is less
remove() used.

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

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

2781. Iterator<T> iterator()

It returns the iterator over the elements of type T.


Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.

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

To instantiate the List interface, we must use :

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


2783. List <data-type> list2 = new LinkedList();
2784. List <data-type> list3 = new Vector();
2785. List <data-type> list4 = new Stack();

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

The classes that implement the List interface are given below.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
2786. import java.util.*;
2787. class TestJavaCollection1{
2788. public static void main(String args[]){
2789. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
2790. list.add("Ravi");//Adding object in arraylist
2791. list.add("Vijay");
2792. list.add("Ravi");
2793. list.add("Ajay");
2794. //Traversing list through Iterator
2795. Iterator itr=list.iterator();
2796. while(itr.hasNext()){
2797. System.out.println(itr.next());
2798. }
2799. }
2800. }

Output:
ADVERTISEMENT

Ravi
Vijay
Ravi
Ajay

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

Consider the following example.

2801. import java.util.*;


2802. public class TestJavaCollection2{
2803. public static void main(String args[]){
2804. LinkedList<String> al=new LinkedList<String>();
2805. al.add("Ravi");
2806. al.add("Vijay");
2807. al.add("Ravi");
2808. al.add("Ajay");
2809. Iterator<String> itr=al.iterator();
2810. while(itr.hasNext()){
2811. System.out.println(itr.next());
2812. }
2813. }
2814. }
ADVERTISEMENT
ADVERTISEMENT

Output:

Ravi
Vijay
Ravi
Ajay

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

Consider the following example.

2815. import java.util.*;


2816. public class TestJavaCollection3{
2817. public static void main(String args[]){
2818. Vector<String> v=new Vector<String>();
2819. v.add("Ayush");
2820. v.add("Amit");
2821. v.add("Ashish");
2822. v.add("Garima");
2823. Iterator<String> itr=v.iterator();
2824. while(itr.hasNext()){
2825. System.out.println(itr.next());
2826. }
2827. }
2828. }

Output:

Ayush
Amit
Ashish
Garima

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

Consider the following example.

2829. import java.util.*;


2830. public class TestJavaCollection4{
2831. public static void main(String args[]){
2832. Stack<String> stack = new Stack<String>();
2833. stack.push("Ayush");
2834. stack.push("Garvit");
2835. stack.push("Amit");
2836. stack.push("Ashish");
2837. stack.push("Garima");
2838. stack.pop();
2839. Iterator<String> itr=stack.iterator();
2840. while(itr.hasNext()){
2841. System.out.println(itr.next());
2842. }
2843. }
2844. }

Output:
Ayush
Garvit
Amit
Ashish

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

Queue interface can be instantiated as:

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


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

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

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

Consider the following example.

2847. import java.util.*;


2848. public class TestJavaCollection5{
2849. public static void main(String args[]){
2850. PriorityQueue<String> queue=new PriorityQueue<String>();
2851. queue.add("Amit Sharma");
2852. queue.add("Vijay Raj");
2853. queue.add("JaiShankar");
2854. queue.add("Raj");
2855. System.out.println("head:"+queue.element());
2856. System.out.println("head:"+queue.peek());
2857. System.out.println("iterating the queue elements:");
2858. Iterator itr=queue.iterator();
2859. while(itr.hasNext()){
2860. System.out.println(itr.next());
2861. }
2862. queue.remove();
2863. queue.poll();
2864. System.out.println("after removing two elements:");
2865. Iterator<String> itr2=queue.iterator();
2866. while(itr2.hasNext()){
2867. System.out.println(itr2.next());
2868. }
2869. }
2870. }

Output:

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

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

Deque can be instantiated as:

2871. Deque d = new ArrayDeque();


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

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

Consider the following example.

2872. import java.util.*;


2873. public class TestJavaCollection6{
2874. public static void main(String[] args) {
2875. //Creating Deque and adding elements
2876. Deque<String> deque = new ArrayDeque<String>();
2877. deque.add("Gautam");
2878. deque.add("Karan");
2879. deque.add("Ajay");
2880. //Traversing elements
2881. for (String str : deque) {
2882. System.out.println(str);
2883. }
2884. }
2885. }

Output:
ADVERTISEMENT

Gautam
Karan
Ajay

Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
Set can be instantiated as:

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


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

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

Consider the following example.

2889. import java.util.*;


2890. public class TestJavaCollection7{
2891. public static void main(String args[]){
2892. //Creating HashSet and adding elements
2893. HashSet<String> set=new HashSet<String>();
2894. set.add("Ravi");
2895. set.add("Vijay");
2896. set.add("Ravi");
2897. set.add("Ajay");
2898. //Traversing elements
2899. Iterator<String> itr=set.iterator();
2900. while(itr.hasNext()){
2901. System.out.println(itr.next());
2902. }
2903. }
2904. }

Output:

Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends
the HashSet class and implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements.

Consider the following example.

2905. import java.util.*;


2906. public class TestJavaCollection8{
2907. public static void main(String args[]){
2908. LinkedHashSet<String> set=new LinkedHashSet<String>();
2909. set.add("Ravi");
2910. set.add("Vijay");
2911. set.add("Ravi");
2912. set.add("Ajay");
2913. Iterator<String> itr=set.iterator();
2914. while(itr.hasNext()){
2915. System.out.println(itr.next());
2916. }
2917. }
2918. }

Output:

Ravi
Vijay
Ajay

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

The SortedSet can be instantiated as:

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


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

Consider the following example:

2920. import java.util.*;


2921. public class TestJavaCollection9{
2922. public static void main(String args[]){
2923. //Creating and adding elements
2924. TreeSet<String> set=new TreeSet<String>();
2925. set.add("Ravi");
2926. set.add("Vijay");
2927. set.add("Ravi");
2928. set.add("Ajay");
2929. //traversing elements
2930. Iterator<String> itr=set.iterator();
2931. while(itr.hasNext()){
2932. System.out.println(itr.next());
2933. }
2934. }
2935. }

Output:

Ajay
Ravi
Vijay

What are we going to learn in Java Collections Framework


2936. ArrayList class
2937. LinkedList class
2938. List interface
2939. HashSet class
2940. LinkedHashSet class
2941. TreeSet class
2942. PriorityQueue class
2943. Map interface
2944. HashMap class
2945. LinkedHashMap class
2946. TreeMap class
2947. Hashtable class
2948. Sorting
2949. Comparable interface
2950. Comparator interface
2951. Properties class in Java

Java ArrayList

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:

• Java ArrayList class can contain duplicate elements.


• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because the array works on an index basis.
• 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.
• 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:
2952. ArrayList<int> al = ArrayList<int>(); // does not work
2953. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
• 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.

2954. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,


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 with the


extends E> c) 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 the specified


extends E> c) 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 specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void ensureCapacity(int It is used to enhance the capacity of an ArrayList


requiredCapacity) instance.

E get(int index) It is used to fetch the element from the particular


position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.

Object[] toArray() It is used to return an array containing all of the


elements in this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the


elements in this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.


boolean contains(Object o) It returns true if the list contains the specified
element.

int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.

E remove(int index) It is used to remove the element present at the


specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the


specified element.

boolean removeAll(Collection<?> It is used to remove all the elements from the list.
c)

boolean removeIf(Predicate<? It is used to remove all the elements from the list that
super E> filter) satisfies the given predicate.

protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.

void It is used to replace all the elements from the list with
replaceAll(UnaryOperator<E> the specified element.
operator)

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.

E set(int index, E element) It is used to replace the specified element in the list,
present at the specified position.

void sort(Comparator<? super E> It is used to sort the elements of the list on the basis
c) of the specified comparator.

Spliterator<E> spliterator() It is used to create a spliterator over the elements in


a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements that lies within the
toIndex) given range.

int size() It is used to return the number of elements present in


the list.
void trimToSize() It is used to trim the capacity of this ArrayList
instance to be the list's current size.

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in 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.

2955. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

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

2957. import java.util.*;


2958. public class ArrayListExample1{
2959. public static void main(String args[]){
2960. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
2961. list.add("Mango");//Adding object in arraylist
2962. list.add("Apple");
2963. list.add("Banana");
2964. list.add("Grapes");
2965. //Printing the arraylist object
2966. System.out.println(list);
2967. }
2968. }
Test it Now

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator

Let's see an example to traverse ArrayList elements using the Iterator interface.

FileName: ArrayListExample2.java

2969. import java.util.*;


2970. public class ArrayListExample2{
2971. public static void main(String args[]){
2972. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
2973. list.add("Mango");//Adding object in arraylist
2974. list.add("Apple");
2975. list.add("Banana");
2976. list.add("Grapes");
2977. //Traversing list through Iterator
2978. Iterator itr=list.iterator();//getting the Iterator
2979. while(itr.hasNext()){//check if iterator has the elements
Java LinkedList 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:


ADVERTISEMENT
ADVERTISEMENT

• Java LinkedList class can contain duplicate elements.


• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs to occur.
• 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.

Backward Skip 10sPlay VideoForward Skip 10s

LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.

2980. 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 elements of the


extends E> c) specified collection, in the order, they are returned by the
collection's iterator.

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 element) It is used to insert the specified element at the specified
position index in a list.
boolean addAll(Collection<? It is used to append all of the elements in the specified
extends E> c) collection to the end of this list, in the order that they
are returned by the specified collection's iterator.

boolean addAll(Collection<? It is used to append all of the elements in the specified


extends E> c) 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 specified
Collection<? extends E> c) 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.

boolean contains(Object o) It is used to return true if a list contains a specified


element.

Iterator<E> It is used to return an iterator over the elements in a


descendingIterator() deque in reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position


in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first


occurrence of the specified element, or -1 if the list does
not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last


occurrence of the specified element, or -1 if the list does
not contain any element.
ListIterator<E> listIterator(int It is used to return a list-iterator of the elements in
index) proper sequence, starting at the specified position in
the list.

boolean offer(E e) It adds the specified element as the last element of a list.

boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a


list is empty.

E peekLast() It retrieves the last element of a list or returns null if a


list is empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or


returns null if a list is empty.

E pollLast() It retrieves and removes the last element of a list, or


returns null if a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a


list.

E remove() It is used to retrieve and removes the first element of a


list.

E remove(int index) It is used to remove the element at the specified


position in a list.

boolean remove(Object o) It is used to remove the first occurrence of the specified


element in a list.

E removeFirst() It removes and returns the first element from a list.


boolean It is used to remove the first occurrence of the specified
removeFirstOccurrence(Object element in a list (when traversing the list from head to
o) tail).

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element


removeLastOccurrence(Object in a list (when traversing the list from head to tail).
o)

E set(int index, E element) It replaces the element at the specified position in a list
with the specified element.

Object[] toArray() It is used to return an array containing all the elements


in a list in proper sequence (from first to the last
element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the
proper sequence (from first to the last element); the
runtime type of the returned array is that of the
specified array.

int size() It is used to return the number of elements in a list.

Java LinkedList Example

2981. import java.util.*;


2982. public class LinkedList1{
2983. public static void main(String args[]){
2984.
2985. LinkedList<String> al=new LinkedList<String>();
2986. al.add("Ravi");
2987. al.add("Vijay");
2988. al.add("Ravi");
2989. al.add("Ajay");
2990.
2991. Iterator<String> itr=al.iterator();
2992. while(itr.hasNext()){
2993. System.out.println(itr.next());
2994. }
2995. }
2996. }
Output: Ravi
Vijay
Ravi
Ajay

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order.
Both are non-synchronized classes.

However, there are many differences between the ArrayList and LinkedList classes that are
given below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic array LinkedList internally uses a doubly


to store the elements. linked list to store the elements.

2) Manipulation with ArrayList is slow Manipulation with LinkedList is faster


because it internally uses an array. If any than ArrayList because it uses a doubly
element is removed from the array, all the linked list, so no bit shifting is required in
other elements are shifted in memory. memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating


accessing data. data.

5) The memory location for the elements of an The location for the elements of a linked
ArrayList is contiguous. list is not contagious.

6) Generally, when an ArrayList is initialized, There is no case of default capacity in a


a default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.
7) To be precise, an ArrayList is a resizable LinkedList implements the doubly linked
array. list of the list interface.

Example of ArrayList and LinkedList in Java


Let's see a simple example where we are using ArrayList and LinkedList both.

FileName: TestArrayLinked.java

2997. import java.util.*;


2998. class TestArrayLinked{
2999. public static void main(String args[]){
3000.
3001. List<String> al=new ArrayList<String>();//creating arraylist
3002. al.add("Ravi");//adding object in arraylist
3003. al.add("Vijay");
3004. al.add("Ravi");
3005. al.add("Ajay");
3006.
3007. List<String> al2=new LinkedList<String>();//creating linkedlist
3008. al2.add("James");//adding object in linkedlist
3009. al2.add("Serena");
3010. al2.add("Swati");
3011. al2.add("Junaid");
3012.
3013. System.out.println("arraylist: "+al);
3014. System.out.println("linkedlist: "+al2);
3015. }
3016. }

Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the duplicate
elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface. It is
a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward
and backward directions. The implementation classes of List interface are ArrayList,
LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used in Java
programming. The Vector class is deprecated since Java 5.

List Interface declaration

3017. public interface List<E> extends Collection<E>

Java List Methods

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 the specified


extends E> c) collection to the end of a list.

boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

boolean equals(Object o) It is used to compare the specified object with the


elements of a list.

int hashcode() It is used to return the hash code value for a list.

E get(int index) It is used to fetch the element from the particular


position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.


int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.

Object[] toArray() It is used to return an array containing all of the


elements in this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the


elements in this list in the correct order.

boolean contains(Object o) It returns true if the list contains the specified


element

boolean It returns true if the list contains all the specified


containsAll(Collection<?> c) element

int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.

E remove(int index) It is used to remove the element present at the


specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the


specified element.

boolean removeAll(Collection<?> It is used to remove all the elements from the list.
c)

void It is used to replace all the elements from the list with
replaceAll(UnaryOperator<E> the specified element.
operator)

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.

E set(int index, E element) It is used to replace the specified element in the list,
present at the specified position.

void sort(Comparator<? super E> It is used to sort the elements of the list on the basis
c) of specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a
list.

List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given
toIndex) range.

int size() It is used to return the number of elements present in


the list.

Java List vs ArrayList

List is an interface whereas ArrayList is the implementation class of List.

How to create List

The ArrayList and LinkedList classes provide the implementation of List interface. Let's see
the examples to create the List:

Backward Skip 10sPlay VideoForward Skip 10s


3018. //Creating a List of type String using ArrayList
3019. List<String> list=new ArrayList<String>();
3020.
3021. //Creating a List of type Integer using ArrayList
3022. List<Integer> list=new ArrayList<Integer>();
3023.
3024. //Creating a List of type Book using ArrayList
3025. List<Book> list=new ArrayList<Book>();
3026.
3027. //Creating a List of type String using LinkedList
3028. List<String> list=new LinkedList<String>();

In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are
used to specify the type. Here, T denotes the type.
ava 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:


ADVERTISEMENT
ADVERTISEMENT

• HashSet stores the elements by using a mechanism called hashing.


• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
• HashSet is the best approach for search operations.
• 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.

3029. public class HashSet<E> extends AbstractSet<E> implements Set<E>,


Cloneable, Serializable

Constructors of Java HashSet class

S Constructor Description
N

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 set to the given
) float loadFactor) integer value capacity and the specified load factor.

4 HashSet(Collection<? It is used to initialize the hash set by using the elements of


) extends E> c) the collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

S Modifier & Method Description


N 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(Obje It is used to return true if this set contains the


) ct o) 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 elements in


) this set.

7 boolean remove(Obje It is used to remove the specified element from this


) ct o) set if it is present.

8 int size() It is used to return the number of elements in the set.


)

9 Spliterator<E spliterator() It is used to create a late-binding and fail-fast


) > Spliterator over the elements in the set.
Java LinkedHashSet Class

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface.
It inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:


ADVERTISEMENT
ADVERTISEMENT

• Java LinkedHashSet class contains unique elements only like HashSet.


• Java LinkedHashSet class provides all optional set operations and permits null
elements.
• Java LinkedHashSet class is non-synchronized.
• Java LinkedHashSet class maintains insertion order.
Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms of extra
memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion order, go for the
lighter-weight HashMap or the HashSet instead.

Hierarchy of LinkedHashSet class


The LinkedHashSet class extends the HashSet class, which implements the Set interface. The
Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

3030. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>,


Cloneable, Serializable

Constructors of Java LinkedHashSet Class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.

LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the
capacity) given integer value capacity.

LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also
capacity, float fillRatio) called load capacity) of the hash set from its argument.
Java TreeSet class

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:

• Java TreeSet class contains unique elements only like HashSet.


• Java TreeSet class access and retrieval times are quiet fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
• Java TreeSet class contains unique elements only like HashSet.
• Java TreeSet class access and retrieval times are quite fast.
• Java TreeSet class doesn't allow null elements.
• Java TreeSet class is non-synchronized.
• Java TreeSet class maintains ascending order.
• 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.

Backward Skip 10sPlay VideoForward Skip 10s


3031. TreeSet treeSet = new TreeSet();
3032. 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

Let's see the declaration for java.util.TreeSet class.

3033. public class TreeSet<E> extends AbstractSet<E> implements


NavigableSet<E>, Cloneable, 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<? It is used to build a new tree set that contains the elements
extends E> c) of the collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that will be sorted


super E> comparator) according to given comparator.

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the elements of


the given SortedSet.

Java Queue Interface


The interface Queue is available in the java.util package and does extend the Collection
interface. It is used to keep the elements that are processed in the First In First Out (FIFO)
manner. It is an ordered list of objects, where insertion of elements occurs at the end of the
list, and removal of elements occur at the beginning of the list.

Being an interface, the queue requires, for the declaration, a concrete class, and the most
common classes are the LinkedList and PriorityQueue in Java. Implementations done by
these classes are not thread safe. If it is required to have a thread safe implementation,
PriorityBlockingQueue is an available option.

Queue Interface Declaration

3034. public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface

Method Description

boolean It is used to insert the specified element into this queue and return true
add(object) upon success.
boolean It is used to insert the specified element into this queue.
offer(object)

Object It is used to retrieves and removes the head of this queue.


remove()

Object poll() It is used to retrieves and removes the head of this queue, or returns null
if this queue is empty.

Object It is used to retrieves, but does not remove, the head of this queue.
element()

Object peek() It is used to retrieves, but does not remove, the head of this queue, or
returns null if this queue is empty.

Features of a Queue
The following are some important features of a queue.
ADVERTISEMENT
ADVERTISEMENT

• As discussed earlier, FIFO concept is used for insertion and deletion of elements from
a queue.
• The Java Queue provides support for all of the methods of the Collection interface
including deletion, insertion, etc.
• PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are
used most frequently.
• The NullPointerException is raised, if any null operation is done on the
BlockingQueues.
• Those Queues that are present in the util package are known as Unbounded Queues.
• Those Queues that are present in the util.concurrent package are known as bounded
Queues.
• All Queues barring the Deques facilitates removal and insertion at the head and tail
of the queue; respectively. In fact, deques support element insertion and removal at
both ends.
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.

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet()
method.

Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHash LinkedHashMap is the implementation of Map. It inherits HashMap class. It


Map maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains


ascending order.
Useful methods of Map interface

Method Description

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key
in the map only if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.

Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and
values.

void clear() It is used to reset the map.

V compute(K key, BiFunction<? It is used to compute a mapping for the specified


super K,? super V,? extends V> key and its current mapped value (or null if there is
remappingFunction) no current mapping).

V computeIfAbsent(K key, It is used to compute its value using the given


Function<? super K,? extends V> mapping function, if the specified key is not already
mappingFunction) associated with a value (or is mapped to null), and
enters it into this map unless null.

V computeIfPresent(K key, It is used to compute a new mapping given the key


BiFunction<? super K,? super V,? and its current mapped value if the value for the
extends V> remappingFunction) specified key is present and non-null.

boolean containsValue(Object This method returns true if some value equal to the
value) value exists within the map, else return false.

boolean containsKey(Object key) This method returns true if some key equal to the
key exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the
Map.

void forEach(BiConsumer<? super It performs the given action for each entry in the
K,? super V> action) map until all entries have been processed or the
action throws an exception.

V get(Object key) This method returns the object that contains the
value associated with the key.

V getOrDefault(Object key, V It returns the value to which the specified key is


defaultValue) mapped, or defaultValue if the map contains no
mapping for the key.

int hashCode() It returns the hash code value for the Map

boolean isEmpty() This method returns true if the map is empty;


returns false if it contains at least one key.

V merge(K key, V value, If the specified key is not already associated with a
BiFunction<? super V,? super V,? value or is associated with null, associates it with
extends V> remappingFunction) the given non-null value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.

Collection values() It returns a collection view of the values contained


in the map.

int size() This method returns the number of entries in the


map.
Map.Entry Interface
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a
collection-view of the map, whose elements are of this class. It provides methods to get key
and value.

Methods of Map.Entry interface

Method Description

K getKey() It is used to obtain a key.

V getValue() It is used to obtain value.

int hashCode() It is used to obtain hashCode.

V setValue(V value) It is used to replace the value


corresponding to this entry with the
specified value.

boolean equals(Object o) It is used to compare the specified


object with the other existing
objects.

static <K extends Comparable<? super K>,V> It returns a comparator that


Comparator<Map.Entry<K,V>> comparingByKey() compare the objects in natural
order on key.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that


comparingByKey(Comparator<? super K> cmp) compare the objects by key using
the given Comparator.

static <K,V extends Comparable<? super V>> It returns a comparator that


Comparator<Map.Entry<K,V>> compare the objects in natural
comparingByValue() order on value.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that


comparingByValue(Comparator<? super V> cmp) compare the objects by value using
the given Comparator.
Java HashMap

Java HashMap class implements the Map interface which allows us to store key and value
pair, where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the java.util package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to
store the null elements as well, but there should be only one null key. Since Java 5, it is
denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the
AbstractMap class and implements the Map interface.

Points to remember

• Java HashMap contains values based on the key.


• Java HashMap contains only unique keys.
• Java HashMap may have one null key and multiple null values.
• Java HashMap is non synchronized.
• Java HashMap maintains no order.
• The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.
HashMap class declaration

Let's see the declaration for java.util.HashMap class.

3035. public class HashMap<K,V> extends AbstractMap<K,V> implements


Map<K,V>, Cloneable, Serializable

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.

• K: It is the type of keys maintained by this map.


• V: It is the type of mapped values.

Constructors of Java HashMap class

Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements
extends V> m) of the given Map object m.

HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.

HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.

Working of HashMap in Java

What is Hashing
It is the process of converting an object into an integer value. The integer value helps in
indexing and faster searches.
What is HashMap
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It
implements the map interface. It stores the data in the pair of Key and Value. HashMap
contains an array of the nodes, and the node is represented as a class. It uses an array and
LinkedList data structure internally for storing Key and Value. There are four fields in
HashMap.

Before understanding the internal working of HashMap, you must be aware of hashCode()
and equals() method.
ADVERTISEMENT
ADVERTISEMENT

• equals(): It checks the equality of two objects. It compares the Key, whether they are
equal or not. It is a method of the Object class. It can be overridden. If you override
the equals() method, then it is mandatory to override the hashCode() method.
• hashCode(): This is the method of the object class. It returns the memory reference
of the object in integer form. The value received from the method is used as the bucket
number. The bucket number is the address of the element inside the map. Hash code
of null Key is 0.
• Buckets: Array of the node is called buckets. Each node has a data structure like a
LinkedList. More than one node can share the same bucket. It may be different in
capacity.
Insert Key, Value pair in HashMap
We use put() method to insert the Key and Value pair in the HashMap. The default size of
HashMap is 16 (0 to 15).

Example

In the following example, we want to insert three (Key, Value) pair in the HashMap.

3036. HashMap<String, Integer> map = new HashMap<>();


3037. map.put("Aman", 19);
3038. map.put("Sunny", 29);
3039. map.put("Ritesh", 39);
Java LinkedHashMap class

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map
interface.

Points to remember

• Java LinkedHashMap contains values based on the key.


• Java LinkedHashMap contains unique elements.
• Java LinkedHashMap may have one null key and multiple null values.
• Java LinkedHashMap is non synchronized.
• Java LinkedHashMap maintains insertion order.
• The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

LinkedHashMap class declaration

Let's see the declaration for java.util.LinkedHashMap class.

3040. public class LinkedHashMap<K,V> extends HashMap<K,V> implements


Map<K,V>
LinkedHashMap class Parameters

Let's see the Parameters for java.util.LinkedHashMap class.

• K: It is the type of keys maintained by this map.


• V: It is the type of mapped values.

Constructors of Java LinkedHashMap class

Constructor Description

LinkedHashMap() It is used to construct a default


LinkedHashMap.

LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with


the given capacity.

LinkedHashMap(int capacity, float It is used to initialize both the capacity and the
loadFactor) load factor.

LinkedHashMap(int capacity, float It is used to initialize both the capacity and the
loadFactor, boolean accessOrder) load factor with specified ordering mode.

LinkedHashMap(Map<? extends K,? It is used to initialize the LinkedHashMap with


extends V> m) the elements from the given Map class m.
Java TreeMap class

Java TreeMap class is a red-black tree based implementation. It provides an efficient means
of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:


ADVERTISEMENT
ADVERTISEMENT

• Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have multiple null values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.

TreeMap class declaration

Let's see the declaration for java.util.TreeMap class.

3041. public class TreeMap<K,V> extends AbstractMap<K,V> implements


NavigableMap<K,V>, Cloneable, Serializable
TreeMap class Parameters

Let's see the Parameters for java.util.TreeMap class.

• K: It is the type of keys maintained by this map.


• V: It is the type of mapped values.

Constructors of Java TreeMap class

Constructor Description

TreeMap() It is used to construct an empty tree map that will be


sorted using the natural order of its key.

TreeMap(Comparator<? It is used to construct an empty tree-based map that will


super K> comparator) be sorted using the comparator comp.

TreeMap(Map<? extends K,? It is used to initialize a treemap with the entries from m,
extends V> m) which will be sorted using the natural order of the keys.

TreeMap(SortedMap<K,? It is used to initialize a treemap with the entries from the


extends V> m) SortedMap sm, which will be sorted in the same order as
sm.

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

• 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.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or value.
• Java Hashtable class is synchronized.
• 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.

3042. public class Hashtable<K,V> extends Dictionary<K,V> implements


Map<K,V>, Cloneable, Serializable

Hashtable class Parameters

Let's see the Parameters for java.util.Hashtable class.

• K: It is the type of keys maintained by this map.


• 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 specified initial
loadFactor) capacity and loadFactor.

Hashtable(Map<? extends It creates a new hash table with the same mappings as the
K,? extends V> t) given Map.

Difference between HashMap and Hashtable


HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given
below.

HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe Hashtable is synchronized. It is
and can't be shared between many threads without thread-safe and can be shared
proper synchronization code. with many threads.

2) HashMap allows one null key and multiple null Hashtable doesn't allow any
values. null key or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by Hashtable is internally


calling this code synchronized and can't be
Map m = Collections.synchronizedMap(hashMap); unsynchronized.

6) HashMap is traversed by Iterator. Hashtable is traversed by


Enumerator and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not


fail-fast.

8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary


class.

Java EnumSet class


Java EnumSet class is the specialized Set implementation for use with enum types. It inherits
AbstractSet class and implements the Set interface.

EnumSet class hierarchy

The hierarchy of EnumSet class is given in the figure given below.

EnumSet class declaration


Let's see the declaration for java.util.EnumSet class.

3043. public abstract class EnumSet<E extends Enum<E>> extends


AbstractSet<E> implements Cloneable, Serializable
Methods of Java EnumSet class

Method Description

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set containing all
allOf(Class<E> elementType) of the elements in the specified element type.

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set initialized
copyOf(Collection<E> c) from the specified collection.

static <E extends Enum<E>> EnumSet<E> It is used to create an empty enum set with
noneOf(Class<E> elementType) the specified element type.

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set initially
of(E e) containing the specified element.

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set initially
range(E from, E to) containing the specified elements.

EnumSet<E> clone() It is used to return a copy of this set.

Java Comparator interface


Java Comparator interface is used to order the objects of a user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, It compares the first object with the second object.
Object obj2)

public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Collections class
Collections class provides static methods for sorting the elements of a collection. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot
sort the elements of List. Collections class provides methods for sorting the elements of List
type elements also.

Java Comparable interface


Java Comparable interface is used to order the objects of the user-defined class. This
interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements
on the basis of single data member only. For example, it may be rollno, name, age or anything
else.

compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns

Difference between Comparable and Comparator


Comparable and Comparator both are interfaces and can be used to sort collection elements.

However, there are many differences between Comparable and Comparator interfaces that
are given below.

Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple


sequence. In other words, we can sort the sorting sequences. In other words, we
collection on the basis of a single element such can sort the collection on the basis of
as id, name, and price. multiple elements such as id, name, and
price etc.
2) Comparable affects the original class, i.e., Comparator doesn't affect the original
the actual class is modified. class, i.e., the actual class is not modified.

3) Comparable provides compareTo() Comparator provides compare()


method to sort elements. method to sort elements.

4) Comparable is present in java.lang package. A Comparator is present in the java.util


package.

5) We can sort the list elements of Comparable We can sort the list elements of
type by Collections.sort(List) method. Comparator type by
Collections.sort(List, Comparator)
method.

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains insertion order.

However, there are many differences between ArrayList and Vector classes that are given
below.

ArrayList Vector

1) ArrayList is not Vector is synchronized.


synchronized.

2) ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if the number size if the total number of elements exceeds than its
of elements exceeds from its capacity.
capacity.

3) ArrayList is not a legacy class. Vector is a legacy class.


It is introduced in JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized, i.e., in a


non-synchronized. multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.

5) ArrayList uses the Iterator A Vector can use the Iterator interface or
interface to traverse the Enumeration interface to traverse the elements.
elements.
Example of Java ArrayList
Let's see a simple example where we are using ArrayList to store and traverse the elements.

3044. import java.util.*;


3045. class TestArrayList21{
3046. public static void main(String args[]){
3047.
3048. List<String> al=new ArrayList<String>();//creating arraylist
3049. al.add("Sonoo");//adding object in arraylist
3050. al.add("Michael");
3051. al.add("James");
3052. al.add("Andy");
3053.
3054. //traversing elements using Iterator
3055. Iterator itr=al.iterator();
3056. while(itr.hasNext()){
3057. System.out.println(itr.next());
3058. }
3059. }
3060. }

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-

• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections
framework.

Java Vector class Declaration

3061. public class Vector<E>


3062. extends Object<E>
3063. implements List<E>, Cloneable, Serializable

Java Vector Constructors


Vector class supports four types of constructors. These are given below:

S Constructor Description
N

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 specified initial
) capacityIncrement) capacity and capacity increment.

4 Vector( Collection<? extends It constructs a vector that contains the elements of a


) E> c) collection c.

Java Vector Methods

Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-
First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection
of objects. One of them is the Stack class that provides different operations such as push, pop, search,
etc.

In this section, we will discuss the Java Stack class, its methods, and implement the stack data
structure in a Java program. But before moving to the Java Stack class have a quick view of how the
stack works.

The stack data structure has the two most important operations that are push and pop. The push
operation inserts an element into the stack and pop operation removes an element from the top of the
stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Backward Skip 10sPlay VideoForward Skip 10s

Let's remove (pop) 18, 45, and 11 from the stack.


Empty Stack: If the stack has no element is known as an empty stack. When the stack is empty the
value of the top variable is -1.

When we push an element into the stack the top is increased by 1. In the following figure,
ADVERTISEMENT

• Push 12, top=0


• Push 6, top=1
• Push 9, top=2

When we pop an element from the stack the value of top is decreased by 1. In the following figure, we
have popped 9.
The following table shows the different values of the top.

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.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.

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

3065. Stack stk = new Stack();

Or

3066. 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 E The method pushes (insert) an element onto the top of the
item) 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.

peek() E The method looks at the top element of the stack without
removing it.

search(Obj int The method searches the specified object and returns the
ect o) 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

← PrevNext

You might also like