OOPs (Object-Oriented Programming System)
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.
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.
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.
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. }
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.
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.
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.
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:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
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
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.
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
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
Output:
101 Sonoo
102 Amit
File: TestStudent4.java
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.
File: TestEmployee.java
Output:
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
Output:
55
45
• By new keyword
• By newInstance() method
• By clone() method
• By deserialization
• By factory method etc.
If you have to use an object only once, an anonymous object is a good approach. For example:
Output:
Factorial is 120
Output:
55
45
Output:
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.
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
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.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
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 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.
A constructor must not have a return type. A method must have a return type.
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.
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
Output:
111 Karan
111 Karan
Yes, it is the current class instance (You cannot use return type yet it returns a value).
Yes.
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 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.
• 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.
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.
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.
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
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.
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. }}
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.
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
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.
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.
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
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
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
Output:
weeping...
barking...
eating...
Output:
meowing...
eating...
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.
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
Output:78.5
• 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.
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
Emp.java
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
In Java, Method Overloading is not possible by changing the return type of the method only.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
Output:
22
33
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.
Output:
22
24.9
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:
Output:
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:
Output:
If there are matching type arguments in the method, type promotion is not performed.
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
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.
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.
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.
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.
Output:
Bike is running safely
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
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.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
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.
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.
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.
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().
Output:
animal is created
dog is created
Que) What is the use of instance initializer block while we can directly assign a value
in instance data member? For example:
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.
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.
Ans) Yes, final method is inherited but you cannot override it. For Example:
Output:running...
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.
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.
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. }
If you declare any parameter as final, you cannot change the value of it.
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.
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:
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
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:
Note: This example is also given in method overriding but there was no upcasting.
Output:
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Output:
ADVERTISEMENT
eating bread...
eating rat...
eating meat...
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.
Output:
90
Output:
eating
eating fruits
drinking Milk
Understanding Type
Let's understand the type of instance.
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.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
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.
Points to Remember
ADVERTISEMENT
ADVERTISEMENT
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
running safely
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
drawing circle
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 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.
Syntax:
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
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.
Output:
Hello
File: TestInterface1.java
Output:
drawing circle
File: TestInterface2.java
Output:
ADVERTISEMENT
ROI: 9.15
Output:Hello
Welcome
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.
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
Output:
drawing rectangle
default method
File: TestInterfaceStatic.java
Output:
drawing rectangle
27
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:
But there are many differences between abstract class and interface that are given below.
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.
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.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
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%).
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
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
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
If you are not using any IDE, you need to follow the syntax given below:
For example
ADVERTISEMENT
ADVERTISEMENT
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
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.
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
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.
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. }
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. }
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.
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.
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.
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.
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.
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.
File: Student.java
File: Test.java
Output:
vijay
Read-Only class
Now, you can't change the value of the college data member which is "AKG".
Write-Only class
Now, you can't get the value of the college, you can only change the value of college data
member.
Let's see another example of encapsulation that has only four fields with its setter and getter
methods.
File: Account.java
File: TestAccount.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 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).
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:
• 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:
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.
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.
Output:
3 3 3
Output:
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.
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.
N Object Class
o
.
2 Object is a real world entity such as pen, laptop, Class is a group of similar
) mobile, bed, keyboard, mouse, chair etc. objects.
4 Object is created through new keyword mainly e.g. Class is declared using class
) Student s1=new Student(); keyword e.g.
class Student{}
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:
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:
is same as:
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.
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.
1) String Literal
Java String literal is created by using double quotes. For Example:
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:
Note: String objects are stored in a special memory area known as the "string constant pool".
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
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
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.
N Method Description
o
.
2 int indexOf(int ch, int fromIndex) It returns the specified char value
0 index starting with given index.
Let's try to understand the concept of immutability by the example given below:
Testimmutablestring.java
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
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
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.
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.
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
• 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
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
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.
2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
Output:
true
false
Teststringcomparison4.java
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.
You can get substring from the given String object by one of the two methods:
In case of String:
• startIndex: inclusive
• endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because
end index is exclusive).
TestSubstring.java
Output:
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.
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.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
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 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)
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. }
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
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 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.
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. }
N String StringBuffer
o
.
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.
5 String class uses String constant pool. StringBuffer uses Heap memory
)
Performance Test of String and StringBuffer
3 StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
)
StringBuffer Example
BufferTest.java
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.
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
Student.java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
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?
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
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.
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.
JavaExceptionExample.java
Output:
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
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.
1647. try{
1648. //code that may throw an exception
1649. }catch(Exception_class_Name ref){}
1650. try{
1651. //code that may throw an exception
1652. }finally{}
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:
But if the application programmer handles the exception, the normal flow of the application
is maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
Output:
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.
Example 2
TryCatchExample2.java
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
MultipleCatchBlock1.java
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 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.
Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if
any).
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
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.
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.
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.
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
TestThrow3.java
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.
Testthrows1.java
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.
In case we handle the exception, the code will be executed fine whether exception occurs
during the program or not.
Testthrows2.java
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
.
Output:
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
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.
Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception.
TestExceptionChild.java
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
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
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
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.
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?
Type Description
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:
TestAnonymousInner.java
If you want to invoke the methods of the local inner class, you must instantiate this class
inside the method.
LocalInner1.java
• It can access static data members of the outer class, including private.
• The static nested class cannot access non-static (instance) data members or
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
Multithreading in Java
• Multithreading
• Multitasking
• Process-based multitasking
• Thread-based multitasking
• What is Thread
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
• 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.
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.
23 void checkAccess() It
) determines
if the
currently
running
thread has
permission
to modify
the thread.
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
2036. New
2037. Active
2038. Blocked / Waiting
2039. Timed Waiting
2040. Terminated
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.
It represents the runnable state.It means a thread is waiting in the queue to run.
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.
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.
FileName: ThreadState.java
Output:
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.
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
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().
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.
FileName: Multi.java
Output:
thread is running...
FileName: Multi3.java
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.
We can directly use the Thread class to spawn new threads using the constructors defined
above.
FileName: MyThread1.java
Output:
My first thread
4) Using the Thread Class: Thread(Runnable r, String name)
FileName: MyThread2.java
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.
In this scheduling algorithm, the scheduler picks the threads thar arrive first in the runnable
queue. Observe the following table:
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.
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.
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:
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.
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.
The following example shows how one can use the sleep() method on the custom thread.
FileName: TestSleepMethod1.java
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.
FileName: TestSleepMethod2.java
FileName: TestCallRun1.java
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.
Syntax:
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.
FileName: ThreadJoinExample.java
FileName: ThreadPriorityExample.java
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.
• 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.
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.
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.
Better performance It saves time because there is no need to create a new thread.
It is used in Servlet and JSP where the container creates a thread pool to process the request.
FileName: TestMultitasking1.java
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.
• 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.
N Method Description
o
.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
There are two types of synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
TestSynchronization1.java
Output:
5
100
10
200
15
300
20
400
25
500
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
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
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
Syntax
TestSynchronizedBlock1.java
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.
In this example we have used synchronized keyword on the static method to perform static
synchronization.
TestSynchronization4.java
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
• 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(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:
3) notifyAll() method
Syntax:
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.
Test.java
TestInterruptingThread1.java
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).
PauseNext
Unmute
Current Time 0:13
/
Duration 18:10
Loaded: 5.14%
Â
Fullscreen
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
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?
N Method Description
o
.
8 public void clear() It removes the total number of elements from the
collection.
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.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
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.
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.
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.
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.
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.
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.
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.
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.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
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:
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.
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.
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.
Output:
Ajay
Ravi
Vijay
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.
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.
Constructors of ArrayList
Constructor Description
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 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.
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.
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.
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.
List<E> subList(int fromIndex, int It is used to fetch all the elements that lies within the
toIndex) given range.
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.
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.
FileName: ArrayListExample1.java
Output:
Let's see an example to traverse ArrayList elements using the Iterator interface.
FileName: ArrayListExample2.java
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.
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.
Constructor Description
Method Description
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(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.
boolean offer(E e) It adds the specified element as the last element of a list.
E set(int index, E element) It replaces the element at the specified position in a list
with the specified 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.
However, there are many differences between the ArrayList and LinkedList classes that are
given below.
ArrayList LinkedList
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.
5) The memory location for the elements of an The location for the elements of a linked
ArrayList is contiguous. list is not contagious.
FileName: TestArrayLinked.java
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.
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in 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.
int hashcode() It is used to return the hash code value for a list.
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.
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.
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see
the examples to create the List:
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 HashSet class extends AbstractSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.
S Constructor Description
N
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.
2 void clear() It is used to remove all of the elements from the set.
)
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface.
It inherits the HashSet class and implements the Set interface.
Constructor Description
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.
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.
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.
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.
Constructor Description
TreeSet(Collection<? It is used to build a new tree set that contains the elements
extends E> c) of the collection c.
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.
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 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.
A Map is useful if you have to search, update or delete elements on the basis of a key.
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.
Method Description
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.
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.
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.
int hashCode() It returns the hash code value for the Map
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.
Method Description
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
As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.
HashMap class declaration
Constructor Description
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.
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.
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
Constructor Description
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.
Java TreeMap class is a red-black tree based implementation. It provides an efficient means
of storing key-value pairs in sorted order.
• 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.
Constructor Description
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.
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
Constructor Description
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.
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.
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.
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.
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.
public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
However, there are many differences between Comparable and Comparator interfaces that
are given below.
Comparable Comparator
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.
However, there are many differences between ArrayList and Vector classes that are given
below.
ArrayList Vector
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.
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.
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.
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections
framework.
S Constructor Description
N
3 vector(int initialCapacity, int It constructs an empty vector with the specified initial
) capacityIncrement) capacity and capacity increment.
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.
When we push an element into the stack the top is increased by 1. In the following figure,
ADVERTISEMENT
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.
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the Stack class.
Or
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.
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.
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