0% found this document useful (0 votes)
3 views97 pages

Module 2

The document discusses abstract classes and interfaces in Java, explaining their definitions, purposes, and differences. It highlights how abstraction allows hiding implementation details while showing only functionality to users, and outlines ways to achieve abstraction through abstract classes and interfaces. Additionally, it covers examples of both concepts, including their usage in real-world scenarios and the enhancements introduced in Java 8 and 9.

Uploaded by

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

Module 2

The document discusses abstract classes and interfaces in Java, explaining their definitions, purposes, and differences. It highlights how abstraction allows hiding implementation details while showing only functionality to users, and outlines ways to achieve abstraction through abstract classes and interfaces. Additionally, it covers examples of both concepts, including their usage in real-world scenarios and the enhancements introduced in Java 8 and 9.

Uploaded by

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

Module-II:

Package and Safe Code


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

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

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

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

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


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

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to
change the body of the method.
Example of abstract class

1. abstract class A{}

Abstract Method in Java


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

Example of abstract method

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


Example of Abstract class that has an abstract
method
In this example, Bike is an abstract class that contains only one
abstract method run. Its implementation is provided by the Honda
class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

running safely

Understanding the real scenario of Abstract


class
In this example, Shape is the abstract class, and its implementation
is provided by the Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is


hidden to the end user), and an object of the implementation class
is provided by the factory method.

A factory method is a method that returns the instance of the


class.

In this example, if we create the instance of Rectangle class, draw()


method of Rectangle class will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown
by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided throug
h method, e.g., getShape() method
15. s.draw();
16. }
17. }

drawing circle

Another example of Abstract class in java


File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %
");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %
");
18. }}

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Abstract class having constructor, data


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

File: TestAbstraction2.java

1. //Example of an abstract class that has abstract and non-abstract m


ethods
2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract method
s
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
bike is created
running safely..
gear changed
Rule: If there is an abstract method in a class, that class must be
abstract.

1. class Bike12{
2. abstract void run();
3. }

compile time error

Rule: If you are extending an abstract class that has an abstract


method, you must either provide the implementation of the
method or make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation
of the interface. In such case, the end user may not be forced to
override all the methods of the interface.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
https://www.youtube.com/watch?
v=p_4Dyfplqkw&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=27

Output:I am a
I am b
I am c
I am d

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.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

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


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

Why use Java interface?


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

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.

How to declare an interface?


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

https://www.youtube.com/watch?v=3PJw1UAcGDo

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Java 8 Interface Improvement


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

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.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello

Java Interface Example: Drawable


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

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by me
thod e.g. getDrawable()
16. d.draw();
17. }}

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. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

Output:

ROI: 9.15

Multiple inheritance in Java by interface


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

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Output:Hello
Welcome

Q) Multiple inheritance is not supported through class


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

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }

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.

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }

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

1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}

Output:

drawing rectangle
default method

Java 8 Static Method in Interface


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

File: TestInterfaceStatic.java

1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}
Output:

drawing rectangle
27

Q) What is marker or tagged interface?


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

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Nested Interface in Java


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

1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
https://www.youtube.com/watch?
v=Mj8uanC2Wn0&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=28

Difference between abstract class and


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

1) Abstract class can have abstract and Interface can have only abstract meth
non-abstract methods.
it can have default and static metho

2) Abstract class doesn't support Interface supports multiple inherita


multiple inheritance.

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

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

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


declare abstract class.

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

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


using keyword "extends".
"implements".

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

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

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

Simply, abstract class achieves partial abstraction (0 to 100%)


whereas interface achieves fully abstraction (100%).
Example of abstract class and interface in
Java
Let's see a simple example where we are using interface and
abstract class both.

1. //Creating interface that has 4 methods


2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one m
ethod of A interface
10. abstract class B implements A{
11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the im
plementation of rest of the methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}

Output:

I am a
I am b
I am c
I am d

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

Package in java can be categorized in two form, built-in package


and user-defined package.

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

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

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so


that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.

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

How to compile java package

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

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated


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

How to run java package program


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

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

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

How to access package from another


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

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

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

The import keyword is used to make the classes and interface of


another package accessible to the current package.

Example of package that import the


packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this
package will be accessible.

Example of package by import


package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

3) Using fully qualified name


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

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

Example of package by import fully


qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello

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

If you import a package, all the classes and interface of that


package will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then
class.

Subpackage in java
Package inside the package is called the subpackage. It should be
created to categorize the package further.

Let's take an example, Sun Microsystem has definded a package


named java that contains many classes like System, String, Reader,
Writer, Socket etc. These classes represent a particular group e.g.
Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io
package, Server and ServerSocket classes in net packages and so
on.

The standard of defining package is domain.company.package


e.g. com.javatpoint.bean or org.sssit.dao.

Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple


Output:Hello subpackage

How to send the class file to another directory


or drive?
There is a scenario, I want to put the class file of A.java source file in
classes folder of c: drive. For example:

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

To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the d
where the class file resides.

e:\sources> set classpath=c:\classes;.;


e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of


java:
The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath
switch of java that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary

o By setting the classpath in the command prompt


o By -classpath switch

o Permanent

o By setting the classpath in the environment variables


o By creating the jar file, that contains all the class files,
and copying the jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and
it must be saved by the public class name.

1. //save as C.java otherwise Compilte Time Error


2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files con
one public class, but keep the package name same. For example:
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}

1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
https://www.youtube.com/watch?
v=OJZrkoR7i88&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=30

Package class
The package class provides methods to get information about the
specification and implementation of a package. It provides methods
such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.

Example of Package class


In this example, we are printing the details of java.lang package by
invoking the methods of package class.

1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificationTitle());
9. System.out.println("Specification Vendor: "+p.getSpecificationVendo
r());
10. System.out.println("Specification Version: "+p.getSpecificationVersi
on());
11.
12. System.out.println("Implementaion Title: "+p.getImplementationTitl
e());
13. System.out.println("Implementation Vendor: "+p.getImplementation
Vendor());
14. System.out.println("Implementation Version: "+p.getImplementatio
nVersion());
15. System.out.println("Is sealed: "+p.isSealed());
16.
17.
18. }
19. }
Output:package name: java.lang
Specification Title: Java Plateform API Specification
Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implemenation Title: Java Runtime Environment
Implemenation Vendor: Sun Microsystems, Inc.
Implemenation Version: 1.6.0_30
IS sealed: false

Access Modifiers in Java


There are two types of modifiers in Java: access
modifiers and non-access modifiers. | Dynamic Method Dispatch

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.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class


contains private data member and private method. We are
accessing these private members from outside the class, so there is
a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

Role of Private Constructor

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

1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

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

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

Example of default access modifier


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

1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

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

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

The protected access modifier can be applied on the data member,


method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

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.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello

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

Example of public access modifier

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

Java Access Modifiers with Method Overriding


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

1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }

The default modifier is more restrictive than protected. That is why,


there is a compile-time error.

https://www.youtube.com/watch?v=b54vqDFjAzk

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism
to handle the runtime errors so that the normal flow of the
application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and
the difference between checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the


normal flow of the application. An exception normally disrupts
the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

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

Suppose there are 10 statements in a Java program and an


exception occurs at statement 5; the rest of the code will not be
executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will
be executed. That is why we use exception handling in Java.

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

Hierarchy of Java Exception classes


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

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as


unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are


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

Keyword Description

try The "try" keyword is used to specify a


z means we can't use try block alone. The try block must be followed by

catch The "catch" block is used to handle the exception. It must be preceded b

means we can't use catch block alone. It can be followed by finally bloc

finally The "finally" block is used to execute the necessary code of the program

whether an exception is handled or not.

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

throws The "throws" keyword is used to declare exceptions. It specifies that the

an exception in the method. It doesn't throw an exception. It is always u

with method signature.

Java Exception Handling Example


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

JavaExceptionExample.java

1. public class JavaExceptionExample{


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

Output:

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


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is


handled by a try-catch block.

Common Scenarios of Java Exceptions


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

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an


ArithmeticException.

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

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on


the variable throws a NullPointerException.

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

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may


result into NumberFormatException. Suppose we have
a string variable that has characters; converting this variable into
digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the


ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

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


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

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an
exception. It must be used within the method.

If an exception occurs at the particular statement in the try block,


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

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

Syntax of Java try-catch


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

Syntax of try-finally block


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

Java catch block


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

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

The JVM firstly checks whether the exception is handled or not. If


exception is not handled, JVM provides a default exception handler
that performs the following tasks:

o Prints out exception description.


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

But if the application programmer handles the exception, the


normal flow of the application is maintained, i.e., rest of the code is
executed.

https://www.youtube.com/watch?
v=9kI0_F41i5Y&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=29

Problem without exception handling


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

Example 1
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }

Output:

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

As displayed in the above example, the rest of the code is not


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

There might be 100 lines of code after the exception. If the


exception is not handled, all the code below the exception won't be
executed.

Solution by exception handling


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

Example 2
TryCatchExample2.java

1. public class TryCatchExample2 {


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

Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is


executed, i.e., the rest of the code statement is printed.

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

TryCatchExample3.java

1. public class TryCatchExample3 {


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

Output:

java.lang.ArithmeticException: / by zero

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

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

TryCatchExample4.java

1. public class TryCatchExample4 {


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

Output:

java.lang.ArithmeticException: / by zero
rest of the code

Example 5
Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }

Output:

Can't divided by zero

Example 6
Let's see an example to resolve the exception in a catch block.

TryCatchExample6.java
1. public class TryCatchExample6 {
2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }

Output:

25

Example 7
In this example, along with try block, we also enclose exception
code in a catch block.

TryCatchExample7.java

1. public class TryCatchExample7 {


2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }

Output:

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

Here, we can see that the catch block didn't contain the exception
code. So, enclose exception code within a try block and use catch
block only to handle the exceptions.

Example 8
In this example, we handle the generated exception (Arithmetic
Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).

TryCatchExample8.java

1. public class TryCatchExample8 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOut
OfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }

Output:

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

Example 9
Let's see an example to handle another unchecked exception.

TryCatchExample9.java

1. public class TryCatchExample9 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

Example 10
Let's see an example to handle checked exception.

Java Catch Multiple Exceptions


Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions,
use java multi-catch block.

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

Flowchart of Multi-catch Block


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

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception o
ccurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }

Output:

Arithmetic Exception occurs


rest of the code

Example 2
MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception o
ccurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time


only one exception occurs and its corresponding catch block is
executed.

MultipleCatchBlock3.java

1. public class MultipleCatchBlock3 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception o
ccurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }

Output:

Arithmetic Exception occurs


rest of the code

Example 4
In this example, we generate NullPointerException, but didn't
provide the corresponding exception type. In such case, the catch
block containing the parent exception class Exception will invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception o
ccurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }

Output:

Parent Exception occurs


rest of the code

Example 5
Let's see an example, to handle the exception without maintaining
the order of exceptions (i.e. from most specific to most general).

MultipleCatchBlock5.java

1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed
");}
8. catch(ArithmeticException e){System.out.println("task1 is comple
ted");}
9. catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }

Output:

Compile-time error

https://www.youtube.com/watch?v=hhK4zGplHTA

Java Nested try block


In Java, using a try block inside another try block is permitted. It is
called as nested try block. Every statement that we enter a
statement in try block, context of that exception is pushed onto the
stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).

Why use nested try block


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

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

Java Nested try Example


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

NestedTryBlock.java

1. public class NestedTryBlock{


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

Output:

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

If none of the catch block specified in the code is unable to handle


the exception, then the Java runtime system will handle the
exception. Then it displays the system generated message for that
exception.

Example 2
Let's consider the following example. Here the try block within
nested try block (inner try block 2) do not handle the exception. The
control is then transferred to its parent try block (inner try block 1).
If it does not handle the exception, then the control is transferred to
the main try block (outer try block) where the appropriate catch
block handles the exception. It is termed as nesting.

NestedTryBlock.java

1. public class NestedTryBlock2 {


2.
3. public static void main(String args[])
4. {
5. // outer (main) try block
6. try {
7.
8. //inner try block 1
9. try {
10.
11. // inner try block 2
12. try {
13. int arr[] = { 1, 2, 3, 4 };
14.
15. //printing the array element out of its bounds
16. System.out.println(arr[10]);
17. }
18.
19. // to handles ArithmeticException
20. catch (ArithmeticException e) {
21. System.out.println("Arithmetic exception");
22. System.out.println(" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. System.out.println("Arithmetic exception");
29. System.out.println("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. System.out.print(e4);
36. System.out.println(" outer (main) try block");
37. }
38. catch (Exception e5) {
39. System.out.print("Exception");
40. System.out.println(" handled in main try-block");
41. }
42. }
43. }

Output:

Java finally block


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

Java finally block is always executed whether an exception is


handled or not. Therefore, it contains all the necessary statements
that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block


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

Why use Java finally block?


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

Usage of Java finally


Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


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

TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }

Output:

Case 2: When an exception occurr but not handled by


the catch block
Let's see the the fillowing example. Here, the code throws an
exception however the catch block cannot handle it. Despite this,
the finally block is executed after the try block and then the
program terminates abnormally.

TestFinallyBlock1.java
1. public class TestFinallyBlock1{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }

Output:
Case 3: When an exception occurs and is handled by
the catch block
Example:

Let's see the following example where the Java code throws an
exception and the catch block handles the exception. Later the
finally block is executed after the try-catch block. Further, the rest
of the code is also executed normally.

TestFinallyBlock2.java

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }

Output:

Rule: For each try block there can be zero or more catch blocks,
but only one finally block.

Note: The finally block will not be executed if the program exits
(either by calling System.exit() or by causing a fatal error that
causes the process to abort).

Java throw Exception


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

Java throw keyword


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

We specify the exception object which is to be thrown. The


Exception has some message with it that provides the error
description. These exceptions may be related to user inputs, server,
etc.

We can throw either checked or unchecked exceptions in Java by


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

We can also define our own set of conditions and throw an


exception explicitly using throw keyword. For example, we can
throw Arithmetic Exception if we divide a number by another
number. Here, we just need to set the condition and throw
exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

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

Let's see the example of throw IOException.

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

Where the Instance must be of type Throwable or subclass of


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

Java throw keyword Example


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

TestThrow1.java

In this example, we have created the validate method that takes


integer value as a parameter. If the age is less than 18, we are
throwing the Arithmetic Exception otherwise print a message
welcome to vote.

1. public class TestThrow1 {


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

Output:

The above code throw an unchecked exception. Similarly, we can


also throw unchecked and user defined exceptions.

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


to handle the exception or declare in throws clause.

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


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

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

1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\
abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }

Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.

TestThrow3.java

1. // class represents user-defined exception


2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-defined exce
ption");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }
Output:

Java Exception Propagation


An exception is first thrown from the top of the stack and if it is not
caught, it drops down the call stack to the previous method. If not
caught there, the exception again drops down to the previous
method, and so on until they are caught or until they reach the very
bottom of the call stack. This is called exception propagation.

Note: By default Unchecked Exceptions are forwarded in calling


chain (propagated).

Exception Propagation Example


TestExceptionPropagation1.java

1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1()
;
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }

Output:

exception handled
normal flow...

In the above example exception occurs in the m() method where it


is not handled, so it is propagated to the previous n() method where
it is not handled, again it is propagated to the p() method where
exception is handled.

Exception can be handled in any method in call stack either in the


main() method, p() method, n() method or m() method.

Note: By default, Checked Exceptions are not forwarded in calling


chain (propagated).

Exception Propagation Example


TestExceptionPropagation1.java

1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked excepti
on
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2()
;
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }

Output:

Compile Time Error

Java throws keyword


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

Exception Handling is mainly used to handle the checked


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

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct


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

Advantage of Java throws keyword


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

It provides information to the caller of the method about the


exception.

Java throws Example


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

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we


must either caught or declare the exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled


the exception using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws
keyword with the method.

Case 1: Handle Exception Using try-catch block


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

Testthrows2.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}

13.
14. System.out.println("normal flow...");
15. }
16. }

Output:

exception handled
normal flow...

Case 2: Declare Exception


o In case we declare the exception, if exception does not occur,
the code will be executed fine.
o In case we declare the exception and the exception occurs, it
will be thrown at runtime because throws does not handle
the exception.

Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//
declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:

device operation performed


normal flow...

B) If exception occurs

Testthrows4.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//
declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:
Difference between throw and throws
Click me for details

Que) Can we rethrow an exception?


Yes, by throwing same exception in catch block.

Difference between throw and throws in


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

There are many differences between throw and throws keywords. A


list of differences between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword Java throws keyword is


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

2. Type of exception Using Using throws


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

3. Syntax The throw keyword is The throws keyword is


followed by an followed by class
instance of Exception names of Exceptions
to be thrown. to be thrown.
4. Declaration throw is used within throws is used with
the method. the method signature.

5. Internal implementation We are allowed to We can declare


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

Java throw Example


TestThrow.java

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, can
not calculate square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num)
);
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }
Output:

Java throws Example


TestThrows.java

1. public class TestThrows {


2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticExce
ption {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }

Output:
Java throw and throws Example
TestThrowAndThrows.java

1. public class TestThrowAndThrows


2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. System.out.println("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticExceptio
n");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. System.out.println("caught in main() method");
20. }
21. }
22. }

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

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

Sr. Key final finally finalize


no.

1. Definition final is the finally is the block finalize is the


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

2. Applicable Final keyword is Finally block is finalize() method is


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

3. Functionali (1) Once (1) finally block finalize method


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

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


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

It's execution is
not dependant on
the exception.

Java final Example


Let's consider the following example where we declare final variable
age. Once declared it cannot be modified.

FinalExampleTest.java

1. public class FinalExampleTest {


2. //declaring final variable
3. final int age = 18;
4. void display() {
5.
6. // reassigning value to age variable
7. // gives compile time error
8. age = 55;
9. }
10.
11. public static void main(String[] args) {
12.
13. FinalExampleTest obj = new FinalExampleTest();
14. // gives compile time error
15. obj.display();
16. }
17. }

Output:

In the above example, we have declared a variable final. Similarly,


we can declare the methods and classes final using the final
keyword.

Java finally Example


Let's see the below example where the Java code throws an
exception and the catch block handles that exception. Later the
finally block is executed after the try-catch block. Further, the rest
of the code is also executed normally.

FinallyExample.java

1. public class FinallyExample {


2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }

Output:

Java finalize Example


FinalizeExample.java

1. public class FinalizeExample {


2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. System.out.println("Hashcode is: " + obj.hashCode());
7. obj = null;
8. // calling the garbage collector using gc()
9. System.gc();
10. System.out.println("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. System.out.println("Called the finalize() method");
16. }
17. }
Output:

Exception Handling with Method


Overriding in Java
There are many rules if we talk about method overriding with
exception handling.

Some of the rules are listed below:

o If the superclass method does not declare an exception


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

o If the superclass method declares an exception,


subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent
exception.

If the superclass method does not declare an exception


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

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

TestExceptionChild.java

1. import java.io.*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. System.out.println("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. System.out.println("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. p.msg();
21. }
22. }

Output:

Rule 2: If the superclass method does not declare an exception,


subclass overridden method cannot declare the checked
exception but can declare unchecked exception.

TestExceptionChild1.java
1. import java.io.*;
2. class Parent{
3. void msg() {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. p.msg();
16. }
17. }

Output:

If the super class method declares an exception


Rule 1: If the superclass method declares an exception, subclass
overridden method can declare the same subclass exception or
no exception but cannot declare parent exception.

Example in case subclass overridden method declares


parent exception
TestExceptionChild2.java

1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. p.msg();
18. }
19. catch (Exception e){}
20.
21. }
22. }

Output:

Example in case subclass overridden method declares


same exception
TestExceptionChild3.java
1. import java.io.*;
2. class Parent{
3. void msg() throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild3 extends Parent {
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild3();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }

Output:

Example in case subclass overridden method declares


subclass exception
TestExceptionChild4.java

1. import java.io.*;
2. class Parent{
3. void msg()throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }

Output:

Example in case subclass overridden method declares


no exception
TestExceptionChild5.java

1. import java.io.*;
2. class Parent {
3. void msg()throws Exception{
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20.
21. }
22. }

Output:

Java Custom Exception


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

Consider the example 1 in which InvalidAgeException class extends


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

In this section, we will learn how custom exceptions are


implemented and used in Java programs.

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that
may occur in the programming. However, we sometimes need to
create custom exceptions.

Following are few of the reasons to use custom exceptions:

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


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

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


class that belongs to java.lang package.

Consider the following example, where we create a custom


exception named WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }

Note: We need to write the constructor that takes the String as


the error message and it is called parent class constructor.

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

TestCustomException1.java

1. // class representing custom exception


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

Output:

Example 2:
TestCustomException2.java

1. // class representing custom exception


2. class MyCustomException extends Exception
3. {
4.
5. }
6.
7. // class that uses custom exception MyCustomException
8. public class TestCustomException2
9. {
10. // main method
11. public static void main(String args[])
12. {
13. try
14. {
15. // throw an object of user defined exception
16. throw new MyCustomException();
17. }
18. catch (MyCustomException ex)
19. {
20. System.out.println("Caught the exception");
21. System.out.println(ex.getMessage());
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }

Output:

Java Inner Classes (Nested Classes)


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

We use inner classes to logically group classes and interfaces in one


place to be more readable and maintainable.
Additionally, it can access all the members of the outer class,
including private data members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of Java inner classes


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

1. 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.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3. Code Optimization: It requires less code to write.

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

o What is the internal code generated by the compiler for


member inner class?
o What are the two ways to create an anonymous inner class?
o Can we access the non-final local variable inside the local
inner class?
o How to access the static nested class?
o Can we define an interface within the class?
o Can we define a class within the interface?

Difference between nested class and inner


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

Types of Nested classes


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

o Non-static nested class (inner class)

1. Member inner class


2. Anonymous inner class
3. Local inner class

o Static nested class

Type Description

Member Inner A cl
Class
ass created within class and outside method.

Anonymous A class created for implementing an interface or extending


Inner Class class. The java compiler decides its name.

Local Inner Class A class was created within the method.

Static Nested A static class was created within the class.


Class
Nested Interface An interface created within class or interface.

You might also like