KEMBAR78
Java Notes 2 | PDF | Inheritance (Object Oriented Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
12 views46 pages

Java Notes 2

Inheritance in Java allows one class to acquire the properties of another, with subclasses inheriting from superclasses using the 'extends' keyword. The document explains key concepts such as the 'super' keyword, method overriding, access modifiers, abstract classes, and interfaces, providing examples for each. Additionally, it covers multithreading, highlighting its advantages and the differences between process-based and thread-based multitasking.

Uploaded by

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

Java Notes 2

Inheritance in Java allows one class to acquire the properties of another, with subclasses inheriting from superclasses using the 'extends' keyword. The document explains key concepts such as the 'super' keyword, method overriding, access modifiers, abstract classes, and interfaces, providing examples for each. Additionally, it covers multithreading, highlighting its advantages and the differences between process-based and thread-based multitasking.

Uploaded by

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

Inheritance in Java

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax
of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example
Live Demo
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given
numbers:"+z);
}
}

public class My_Calculation extends Calculation

{
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

The super keyword


The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
 It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
 It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables we
use super keyword as shown below.
super.variable
super.method();
Example
Live Demo
class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class


{
int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub
class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super
class:"+ super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}

Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass Constructor


If a class is inheriting the properties of another class, the subclass automatically
acquires the default constructor of the superclass. But if you want to call a
parameterized constructor of the superclass, you need to use the super keyword as
shown below.
super(values);
Example
Live Demo
class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in super
class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String args[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

Output
The value of the variable named age in super class is: 24

Method Overriding in Java


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

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

Usage of Java Method Overriding


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

o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class

2. The method must have the same parameter as in the parent class.

3. There must be an IS-A relationship (inheritance).

Example of method overriding


class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


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

Output:

Bike is running safely


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

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

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

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

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

Understanding Java Access Modifiers


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

ss Modifier within within package outside package by outside package


class subclass only not subclass

ivate Y N N N

efault Y Y N N

otected Y Y Y N
blic Y Y Y Y

1) Private
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

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

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

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

//save by B.java
package mypack;
import pack.*;

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

4) Public
//save by A.java

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

//save by B.java

package mypack;
import pack.*;

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

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

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

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It cannot be instantiated.

o It can have constructors and static methods also.

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

Example of abstract class

1. abstract class A{}

Abstract Method in Java


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

Example of abstract method

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

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
output:
running safely

Example 2
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getS
hape() method
s.draw();
}
}
Test it Now
drawing circle

Another example of Abstract class in java


abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

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

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

Why use Java interface?


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

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.


o It can be used to achieve loose coupling.

Syntax:
interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}
Ex
interface abc interface abc
{ compile {
int a=10; ----------> public static final int a=10;
void display(); public abstract void display();
} }

Internal addition by the compiler


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

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

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
obj.print();
}
}
Test it Now

Output:

Hello

Example2
interface Drawable

void draw();

//Implementation: by second user

class Rectangle implements Drawable

public void draw()

System.out.println("drawing rectangle");

class Circle implements Drawable

public void draw()

System.out.println("drawing circle");}
}

//Using interface: by third user


class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}}
Test it Now

Output:

drawing circle

Java Interface Example: Bank


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

File: TestInterface2.java

1. interface Bank
2. {
3. float rateOfInterest();
4. }
5. class SBI implements Bank
6. {
7. public float rateOfInterest()
8. {
9. return 9.15f;
}
}
class PNB implements Bank{
public float rateOfInterest()
{
return 9.7f;
}
}
10. class TestInterface2
11. {
12. public static void main(String[] args)
13. {
14. Bank b=new SBI();
15. System.out.println("ROI: "+b.rateOfInterest());
16. }
17. }
Test it Now

Output:

ROI: 9.15

Java - Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.

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


Multiprocessing and multithreading, both are used to achieve multitasking.

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


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

Advantages of Java Multithreading


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

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

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


single thread.

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

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.

o A process is heavyweight.

o Cost of communication between the process is high.

o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.

o A thread is lightweight.

o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


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

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.

Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cy
runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New

2. Runnable

3. Running

4. Non-Runnable (Blocked)

5. Terminated

1) New
The thread is in new state if you create an instance of Thread class but before the invocation o

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.

Creating a thread in Java


There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the
example below.

 getName(): It is used for Obtaining a thread’s name


 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

Example(By extending Thread class.)


class aka extends Thread
{
public void run()
{
//task1
for(int j=0;j<5;j++) {
System.out.println("hi"+j);

}
}
class asd
{
public static void main(String args[])
{
aka obj=new aka();
Thread t=new Thread(obj);
t.start();
//task2
for(int i=0;i<5;i++){
System.out.println("hello"+i);

}
}
}

Example(By implementing Runnable interface)

class aka implements Runnable


{
public void run()
{
//task1
for(int j=0;j<5;j++) {
System.out.println("hi"+j);

}
}
class asd
{
public static void main(String args[])
{
aka obj=new aka();
Thread t=new Thread(obj);
t.start();
//task2
for(int i=0;i<5;i++){
System.out.println("hello"+i);

}
}
}
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In mo
schedules the threads according to their priority (known as preemptive scheduling). But it is
depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY

3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


10.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

Java Thread Synchronization


Synchronization is a process of handling resource accessibility by multiple thread
requests. The main purpose of synchronization is to avoid thread interference. At times
when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved
is called synchronization. The synchronization keyword in java creates a block of code
referred to as critical section.
General Syntax:
synchronized (object)

//statement to be synchronized

Every Java object with a critical section of code gets a lock associated with the object.
To enter critical section a thread need to obtain the corresponding object's lock.

Why we need Syncronization?


If we do not use syncronization, and let two or more threads access a shared resource at
the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file temporary.txt which will be used to calculate
some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the
values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now
obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in
above case, once T1 starts using temporary.txt file, this file will be locked(LOCK mode),
and no other thread will be able to access or modify it until T1 returns.

Using Synchronized Methods


Using Synchronized methods is a way to accomplish synchronization. But lets first see
what happens when we do not use synchronization in our program.

Example with no Synchronization


In this example, we are not using synchronization and creating multiple threads that are
accessing display method and produce the random output.
class First

public void display(String msg)

System.out.print ("["+msg);

try

Thread.sleep(1000);

catch(InterruptedException e)

e.printStackTrace();

System.out.println ("]");

}
}

class Second extends Thread

String msg;

First fobj;

Second (First fp,String str)

fobj = fp;

msg = str;

start();

public void run()

fobj.display(msg);

public class Syncro

public static void main (String[] args)

First fnew = new First();

Second ss = new Second(fnew, "welcome");

Second ss1= new Second(fnew,"new");


Second ss2 = new Second(fnew, "programmer");

[welcome [ new [ programmer]

In the above program, object fnew of class First is shared by all the three running
threads(ss, ss1 and ss2) to call the shared method(void display). Hence the result is
nonsynchronized and such situation is called Race condition..

Synchronized Keyword
To synchronize above program, we must synchronize access to the
shared display() method, making it available to only one thread at a time. This is done
by using keyword synchronized with display() method.
synchronized void display (String msg)

Example : implementation of synchronized method


class First

synchronized public void display(String msg)

System.out.print ("["+msg);

try

Thread.sleep(1000);

catch(InterruptedException e)

{
e.printStackTrace();

System.out.println ("]");

class Second extends Thread

String msg;

First fobj;

Second (First fp,String str)

fobj = fp;

msg = str;

start();

public void run()

fobj.display(msg);

public class MyThread

public static void main (String[] args)


{

First fnew = new First();

Second ss = new Second(fnew, "welcome");

Second ss1= new Second(fnew,"new");

Second ss2 = new Second(fnew, "programmer");

[welcome]

[programmer]

[new]

Using Synchronized block


If want to synchronize access to an object of a class or only a part of a method to be
synchronized then we can use synchronized block for it. It is capable to make any part of
the object and method synchronized.

Example
In this example, we are using synchronized block that will make the display method
available for single thread at a time.

class First

public void display(String msg)

System.out.print ("["+msg);

try

{
Thread.sleep(1000);

catch(InterruptedException e)

e.printStackTrace();

System.out.println ("]");

class Second extends Thread

String msg;

First fobj;

Second (First fp,String str)

fobj = fp;

msg = str;

start();

public void run()

synchronized(fobj) //Synchronized block

fobj.display(msg);
}

public class MyThread

public static void main (String[] args)

First fnew = new First();

Second ss = new Second(fnew, "welcome");

Second ss1= new Second (fnew,"new");

Second ss2 = new Second(fnew, "programmer");

[welcome]

[new]

[programmer]

Because of synchronized block this program gives the expected output.

Difference between synchronized keyword and


synchronized block
When we use synchronized keyword with a method, it acquires a lock in the object for
the whole method. It means that no other thread can use any synchronized method until
the current thread, which has invoked it's synchronized method, has finished its
execution.
synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword. This means that no other thread can acquire a lock on the locked
object until the synchronized block exits. But other threads can access the rest of the
code of the method.

Which is more preferred - Synchronized method or


Synchronized block?
In Java, synchronized keyword causes a performance cost. A synchronized method in
Java is very slow and can degrade performance. So we must use synchronization
keyword in java when it is necessary else, we should use Java synchronized block that is
used for synchronizing critical section only.

Thread Deadlock in Java

Deadlock is a situation of complete Lock, when no thread can complete its execution
because lack of resources. In the above picture, Thread 1 is holding a resource R1, and
need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs
R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in
a deadlock.

Example
In this example, multiple threads are accessing same method that leads to deadlock
condition. When a thread holds the resource and does not release it then other thread
will wait and in deadlock condition wait time is never ending.
class Pen{}
class Paper{}

public class Write {

public static void main(String[] args)

final Pen pn =new Pen();

final Paper pr =new Paper();

Thread t1 = new Thread() {

public void run()

synchronized(pn)

System.out.println("Thread1 is holding Pen");

try{

Thread.sleep(1000);

catch(InterruptedException e){

// do something

synchronized(pr)

System.out.println("Requesting for Paper");

}
}

};

Thread t2 = new Thread() {

public void run()

synchronized(pr)

System.out.println("Thread2 is holding Paper");

try {

Thread.sleep(1000);

catch(InterruptedException e){

// do something

synchronized(pn)

System.out.println("requesting for Pen");

};

t1.start();

t2.start();
}

Thread1 is holding Pen

Thread2 is holding Paper

Java Interthread Communication


Java provide benefits of avoiding thread pooling using inter-thread communication.
The wait(), notify(), and notifyAll() methods of Object class are used for this purpose.
These method are implemented as final methods in Object, so that all classes have
them. All the three method can be called only from within a synchronized context

 wait() tells calling thread to give up monitor and go to sleep until some other

thread enters the same monitor and call notify.


 notify() wakes up a thread that called wait() on same object.

 notifyAll() wakes up all the thread that called wait() on same object.

Difference between wait() and sleep()


wait() sleep()

called from synchronised block no such requirement

monitor is released monitor is not released

gets awake when notify() or notifyAll() method is does not get awake when notify() or notify
called. is called
wait() is generaly used on condition sleep() method is simply used to put your
sleep.

Example:

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

In this page, we will learn about Java exceptions, its type and the difference between
checked and unchecked exceptions.

What is Exception in Java


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown
at runtime.

What is Exception Handling


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are
given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

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

Java Exception Keywords


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

Keyword Description

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

Catch The "catch" block is used to handle the exception. It must be preceded by try b
catch block alone. It can be followed by finally block later.

Finally The "finally" block is used to execute the important code of the program. It is ex
is handled or not.

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

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

Java Exception Handling Example


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

public class JavaExceptionExample{


public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{

System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch
blocks looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

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.

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Java finally block


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

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
Example
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

You might also like