0% found this document useful (0 votes)
2 views39 pages

Module I - Basic Java 2

The document provides an overview of inheritance, method overriding, abstract classes, and interfaces in Java. It explains key concepts such as single, multilevel, and hierarchical inheritance, as well as the importance of code reusability and polymorphism. Additionally, it discusses the limitations of multiple inheritance in Java and illustrates the use of abstract classes and interfaces for achieving abstraction and loose coupling.

Uploaded by

Chandramani
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)
2 views39 pages

Module I - Basic Java 2

The document provides an overview of inheritance, method overriding, abstract classes, and interfaces in Java. It explains key concepts such as single, multilevel, and hierarchical inheritance, as well as the importance of code reusability and polymorphism. Additionally, it discusses the limitations of multiple inheritance in Java and illustrates the use of abstract classes and interfaces for achieving abstraction and loose coupling.

Uploaded by

Chandramani
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

OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem.

CSE

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

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

For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A [Link] means that Programmer is a
type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java:

 single,
 multilevel
 hierarchical.

Note: Multiple inheritance is not supported in java through [Link] a class extends multiple
classes i.e. known as multiple inheritance.

By Er. RAHAMATULLA (Assistant Professor) Page 1 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Multiple inheritances in java


To reduce the complexity and simplify the language, multiple inheritance is not supported in
[Link] a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there will
be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
class A{

void msg(){[Link]("Hello");}

class B{

void msg(){[Link]("Welcome");}

class C extends A,B{//suppose if it were

Public Static void main(String args[]){

C obj=new C();

[Link]();//Now which msg() method would be invoked?

Test it Now

Compile Time Error

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 subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

By Er. RAHAMATULLA (Assistant Professor) Page 2 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

 method must have same name as in the parent class


 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).

Understanding the problem without method overriding

class Vehicle{

void run(){[Link]("Vehicle is running");}

class Bike extends Vehicle{

public static void main(String args[]){

Bike obj = new Bike();

[Link]();

Test it Now

Output:Vehicle is running

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

Example of method overriding

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

class Vehicle{

void run(){[Link]("Vehicle is running");}

class Bike2 extends Vehicle{

void run(){[Link]("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2();

[Link]();

Output:Bike is running safely

Real example of Java Method Overriding

By Er. RAHAMATULLA (Assistant Professor) Page 3 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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

Java method overriding example of bank

class Bank{

int getRateOfInterest(){return 0;}

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

class Test2{

public static void main(String args[]){

SBI s=new SBI();

ICICI i=new ICICI();

AXIS a=new AXIS();

[Link]("SBI Rate of Interest: "+[Link]());

[Link]("ICICI Rate of Interest: "+[Link]());

[Link]("AXIS Rate of Interest: "+[Link]());

Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Static method is bound with class whereas instance method is bound with object. Static belongs
to class area and instance belongs to heap area.

By Er. RAHAMATULLA (Assistant Professor) Page 4 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with 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 important things to the user and hides the internal details
for example sending sms, you just 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.

There are two ways to achieve abstraction in java

 Abstract class (0 to 100%)


 Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

Example abstract class

abstract class A{}

abstract method

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

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

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

abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){[Link]("running safely..");}

public static void main(String args[]){

Bike obj = new Honda4();

[Link]();

By Er. RAHAMATULLA (Assistant Professor) Page 5 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Test it Now

running safely..

Understanding the real scenario of abstract class

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

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

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

File: [Link]

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(){[Link]("drawing rectangle");}

class Circle1 extends Shape{

void draw(){[Link]("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 real scenario, object is provided through method e.g. getShape()
method

[Link]();

Test it Now

drawing circle

Another example of abstract class in java

By Er. RAHAMATULLA (Assistant Professor) Page 6 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

File: [Link]

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

[Link]("Rate of Interest is: "+[Link]()+" %");

b=new PNB();

[Link]("Rate of Interest is: "+[Link]()+" %");

}}

Test it Now

Rate of Interest is: 7 %

Rate of Interest is: 8 %

Abstract class having constructor, data member, methods etc.

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

File: [Link] //example of abstract class that have method body

abstract class Bike{

Bike(){[Link]("bike is created");}

abstract void run();

void changeGear(){[Link]("gear changed");}

class Honda extends Bike{

By Er. RAHAMATULLA (Assistant Professor) Page 7 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

void run(){[Link]("running safely..");}

class TestAbstraction2{

public static void main(String args[]){

Bike obj = new Honda();

[Link]();

[Link]();

Test it Now

bike is created

running safely..

gear changed

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

class Bike12{

abstract void run();

Test it Now

compile time error

Rule: If you are extending any abstract class that have abstract method, you must either provide t

Another real scenario of abstract class

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

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

interface A{

void a();

void b();

void c();

void d();

abstract class B implements A{

By Er. RAHAMATULLA (Assistant Professor) Page 8 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

public void c(){[Link]("I am C");}

class M extends B{

public void a(){[Link]("I am a");}

public void b(){[Link]("I am b");}

public void d(){[Link]("I am d");}

class Test5{

public static void main(String args[]){

A a=new M();

a.a();

a.b();

a.c();

a.d();

}}

Test it Now

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

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

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

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

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
 The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.

By Er. RAHAMATULLA (Assistant Professor) Page 9 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

interface

Understanding relationship between classes and interfaces


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

 In other words, Interface fields are public, static and final bydefault, and methods are
public and abstract.
Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in the
A class.

interface printable{

void print();

class A6 implements printable{

public void print(){[Link]("Hello");}

public static void main(String args[]){

A6 obj = new A6();

[Link]();

Test it Now

Output:Hello

Multiple inheritances in Java by interface

By Er. RAHAMATULLA (Assistant Professor) Page 10 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

multiple inheritance in java

interface Printable{

void print();

interface Showable{

void show();

class A7 implements Printable,Showable{

public void print(){[Link]("Hello");}

public void show(){[Link]("Welcome");}

public static void main(String args[]){

A7 obj = new A7();

[Link]();

[Link]();

Test it Now

Output:Hello

Welcome

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of
class. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:

interface Printable{

void print();

By Er. RAHAMATULLA (Assistant Professor) Page 11 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

interface Showable{

void print();

class TestTnterface1 implements Printable,Showable{

public void print(){[Link]("Hello");}

public static void main(String args[]){

TestTnterface1 obj = new TestTnterface1();

[Link]();

Test it Now

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 interface but one interface extends another interface .

interface Printable{

void print();

interface Showable extends Printable{

void show();

class Testinterface2 implements Showable{

public void print(){[Link]("Hello");}

public void show(){[Link]("Welcome");}

public static void main(String args[]){

Testinterface2 obj = new Testinterface2();

[Link]();

[Link]();

By Er. RAHAMATULLA (Assistant Professor) Page 12 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Test it Now

Hello

Welcome

An interface that have no member is known as 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.

//How Serializable interface is written?

public interface Serializable{

Nested Interface in Java

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

interface printable{

void print();

interface MessagePrintable{ Java Nested Interface

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

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.

Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.

Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface

interface interface_name{

... interface nested_interface_name{

... }

Syntax of nested interface which is declared within the class

class class_name{

... interface nested_interface_name{

By Er. RAHAMATULLA (Assistant Professor) Page 13 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

... }

Example of nested interface which is declared within the interface

In this example, we are going to learn how to declare the nested interface and how we can access
it.

interface Showable{

void show();

interface Message{

void msg();

class TestNestedInterface1 implements [Link]{

public void msg(){[Link]("Hello nested interface");}

public static void main(String args[]){

[Link] message=new TestNestedInterface1();//upcasting here

[Link]();

Test it Now

download the example of nested interface

Output:hello nested interface

As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the room,
we cannot access the almirah directly because we must enter the room first. In collection
frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of
Map i.e. accessed by [Link].

Internal code generated by the java compiler for nested interface Message

The java compiler internally creates public and static interface as displayed below:.

public static interface Showable$Message

public abstract void msg();

By Er. RAHAMATULLA (Assistant Professor) Page 14 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example of nested interface which is declared within the class

Let's see how can we define an interface inside the class and how can we access it.

class A{

interface Message{

void msg();

class TestNestedInterface2 implements [Link]{

public void msg(){[Link]("Hello nested interface");}

public static void main(String args[]){

[Link] message=new TestNestedInterface2();//upcasting here

[Link]();

Test it Now

Output:hello nested interface

Class inside interface

interface M{

class A{}

void msg();

Difference between abstract class and interface

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

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

By Er. RAHAMATULLA (Assistant Professor) Page 15 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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.

//Creating <a href="#">interface</a> that has 4 methods

<a href="#">interface</a> A{

void a();//bydefault, public and abstract

void b();

void c();

void d();

//Creating abstract class that provides the implementation of one method of A interface

abstract class B implements A{

public void c(){[Link]("I am C");}

//Creating subclass of abstract class, now we need to provide the implementation of rest of the
methods

class M extends B{

public void a(){[Link]("I am a");}

public void b(){[Link]("I am b");}

By Er. RAHAMATULLA (Assistant Professor) Page 16 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

public void d(){[Link]("I am d");}

//Creating a test class that calls the methods of A interface

class Test5{

public static void main(String args[]){

A a=new M();

a.a();

a.b();

a.c();

a.d();

}}

Test it Now

Output:

I am a

I am b

I am c

I am d

Java Package
Package class

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

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

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

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

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.

By Er. RAHAMATULLA (Assistant Professor) Page 17 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

3) Java package removes naming collision.

package in java

Simple example of java package

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

//save as [Link]

package mypack;

public class Simple{

public static void main(String args[]){

[Link]("Welcome to package");

How to compile java package

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

javac -d directory javafilename

For example

javac -d . [Link]

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. [Link] etc to run the class.

To Compile: javac -d . [Link]

To Run: java [Link]

Output:Welcome to package

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

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

 import package.*;
 import [Link];
 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.

By Er. RAHAMATULLA (Assistant Professor) Page 18 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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

Example of package that import the packagename.*

//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

Output:Hello

2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]

//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.A;

class B{

public static void main(String args[]){

By Er. RAHAMATULLA (Assistant Professor) Page 19 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

A obj = new A();

[Link]();

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. [Link] and [Link] packages
contain Date class.

Example of package by import fully qualified name

//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

[Link]();

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.

sequence of package

Subpackage in java

By Er. RAHAMATULLA (Assistant Professor) Page 20 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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 [Link] e.g. [Link] or


[Link].

Example of Subpackage

package [Link];

class Simple{

public static void main(String args[]){

[Link]("Hello subpackage");

To Compile: javac -d . [Link]

To Run: java [Link]

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 [Link] source file in classes folder of c: drive.
For example:

how to put class file in another package

//save as [Link]

package mypack;

public class Simple{

public static void main(String args[]){

[Link]("Welcome to package");

To Compile:

e:\sources> javac -d c:\classes [Link]

To Run:

By Er. RAHAMATULLA (Assistant Professor) Page 21 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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

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

e:\sources> java [Link]

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
were to look for class file. For example:

e:\sources> java -classpath c:\classes [Link]

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.

Temporary

 By setting the classpath in the command prompt


 By -classpath switch

Permanent

 By setting the classpath in the environment variables


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

//save as [Link] otherwise Compilte Time Error

class A{}

class B{}

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 containing one
public class, but keep the package name same. For example:

//save as [Link]

package javatpoint;

public class A{}

//save as [Link]

package javatpoint;

public class B{}

By Er. RAHAMATULLA (Assistant Professor) Page 22 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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 [Link] package by invoking the methods of
package class.
class PackageInfo{

public static void main(String args[]){

Package p=[Link]("[Link]");

[Link]("package name: "+[Link]());

[Link]("Specification Title: "+[Link]());

[Link]("Specification Vendor: "+[Link]());

[Link]("Specification Version: "+[Link]());

[Link]("Implementaion Title: "+[Link]());

[Link]("Implementation Vendor: "+[Link]());

[Link]("Implementation Version: "+[Link]());

[Link]("Is sealed: "+[Link]());

Output:package name: [Link]

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

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 exception, its type and the difference between checked and
unchecked exceptions.

What is exception

By Er. RAHAMATULLA (Assistant Professor) Page 23 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Dictionary Meaning: Exception is an abnormal condition.

In java, 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 ClassNotFound, IO, SQL,
Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

statement 1;

statement 2;

statement 3;

statement 4;

statement 5;//exception occurs

statement 6;

statement 7;

statement 8;

statement 9;

statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest
of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.

Hierarchy of Java Exception classes

By Er. RAHAMATULLA (Assistant Professor) Page 24 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

 Checked Exception
 Unchecked Exception

Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions [Link], SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

By Er. RAHAMATULLA (Assistant Professor) Page 25 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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

Common scenarios where exceptions may occur

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

1) Scenario where ArithmeticException occurs

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

int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.

String s=null;

[Link]([Link]());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.

String s="abc";

int i=[Link](s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];

a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

 try
 catch
 finally
 throw
 throws

Java try-catch

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

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

Application programming interface (API) to support the development of new applications by


freelance developers and other third-parties

By Er. RAHAMATULLA (Assistant Professor) Page 26 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Syntax of java try-catch

try{

//code that may throw exception

}catch(Exception_class_Name ref){}

Syntax of try-finally block

try{

//code that may throw exception

}finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch block with a single try.

Problem without exception handling

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

public class Testtrycatch1{

public static void main(String args[]){

int data=50/0;//may throw exception

[Link]("rest of the code...");

Test it Now

Output:

Exception in thread main [Link]:/ by zero

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

There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

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

public class Testtrycatch2{

public static void main(String args[]){

try{

int data=50/0;

By Er. RAHAMATULLA (Assistant Professor) Page 27 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

}catch(ArithmeticException e){[Link](e);}

[Link]("rest of the code...");

Test it Now

Output:

Exception in thread main [Link]:/ by zero

rest of the code...

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

Internal working of java try-catch block

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

Prints out exception description.

Prints the stack trace (Hierarchy of methods where the exception occurred).

Causes the program to terminate.

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

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.

public class TestMultipleCatchBlock{

public static void main(String args[]){

try{

int a[]=new int[5];

a[5]=30/0;

catch(ArithmeticException e){[Link]("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}

catch(Exception e){[Link]("common task completed");}

[Link]("rest of the code...");

By Er. RAHAMATULLA (Assistant Professor) Page 28 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Test it Now

Output:task1 completed

rest of the code...

Rule: At a time only one Exception is occured and at a time only one catch block is executed.

Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .

class TestMultipleCatchBlock1{

public static void main(String args[]){

try{

int a[]=new int[5];

a[5]=30/0;

catch(Exception e){[Link]("common task completed");}

catch(ArithmeticException e){[Link]("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}

[Link]("rest of the code...");

Test it Now

Output:

Compile-time error

Java Nested try block

The try block within a try block is known as nested try block in java.

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

Syntax:..

try

statement 1;

statement 2;

try

By Er. RAHAMATULLA (Assistant Professor) Page 29 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

statement 1;

statement 2;

catch(Exception e)

catch(Exception e)

.... Java nested try example

class Excep6{

public static void main(String args[]){

try{

try{

[Link]("going to divide");

int b =39/0;

}catch(ArithmeticException e){[Link](e);}

try{

int a[]=new int[5];

a[5]=4;

}catch(ArrayIndexOutOfBoundsException e){[Link](e);}

[Link]("other statement);

}catch(Exception e){[Link]("handeled");}

[Link]("normal flow..");

Java finally block

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

By Er. RAHAMATULLA (Assistant Professor) Page 30 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

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

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.

Usage of Java finally

Case 1

class TestFinallyBlock{

public static void main(String args[]){

try{

int data=25/5;

[Link](data);

catch(NullPointerException e){[Link](e);}

finally{[Link]("finally block is always executed");}

[Link]("rest of the code...");

Test it Now

Output:5

finally block is always executed

rest of the code...

Case 2

class TestFinallyBlock1{

public static void main(String args[]){

try{

int data=25/0;

[Link](data);

catch(NullPointerException e){[Link](e);}

finally{[Link]("finally block is always executed");}

By Er. RAHAMATULLA (Assistant Professor) Page 31 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

[Link]("rest of the code...");

Test it Now

Output:finally block is always executed

Exception in thread main [Link]:/ by zero

Case 3

public class TestFinallyBlock2{

public static void main(String args[]){

try{

int data=25/0;

[Link](data);

catch(ArithmeticException e){[Link](e);}

finally{[Link]("finally block is always executed");}

[Link]("rest of the code...");

Test it Now

Output:Exception in thread main [Link]:/ by zero

finally block is always executed

rest of the code...

java throw keyword

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

We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.

throw new IOException("sorry device error);

java throw keyword example

By Er. RAHAMATULLA (Assistant Professor) Page 32 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

1 In this example, we have created the validate method that takes integer value as a
2 parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
3 print a message welcome to vote.
4
5 public class TestThrow1{
6
7 static void validate(int age){
8
9 if(age<18)
10
11 throw new ArithmeticException("not valid");
12
13 else
14
15 [Link]("welcome to vote");
16
17 }
18
19 public static void main(String args[]){
20
21 validate(13);
22
23 [Link]("rest of the code...");
24
25 }
26
27 }
28
29 Test it Now
30
31 Output:
32
33 Exception in thread main [Link]:not valid
34
35 Java Exception propagation
36
37 An exception is first thrown from the top of the stack and if it is not caught, it drops
38 down the call stack to the previous method,If not caught there, the exception again drops
39 down to the previous method, and so on until they are caught or until they reach the very
40 bottom of the call [Link] is called exception propagation.
41
42 Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
43
44 Program of Exception Propagation
45
46 class TestExceptionPropagation1{
47
48 void m(){
49
50 int data=50/0;
51
52 }
53
54 void n(){
55
56 m();
57
58 }
59
60 void p(){

By Er. RAHAMATULLA (Assistant Professor) Page 33 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

try{

n();

}catch(Exception e){[Link]("exception handled");}

public static void main(String args[]){

TestExceptionPropagation1 obj=new TestExceptionPropagation1();

obj.p();

[Link]("normal flow...");

Test it Now

Output:exception handled

normal flow...

exception propagation

In the above example exception occurs in m() method where it is not handled,so it is propagated
to previous n() method where it is not handled, again it is propagated to p() method where
exception is handled.

Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Program which describes that checked exceptions are not propagated

class TestExceptionPropagation2{

void m(){

throw new [Link]("device error");//checked exception

void n(){

m();

void p(){

try{

n();

}catch(Exception e){[Link]("exception handeled");}

By Er. RAHAMATULLA (Assistant Professor) Page 34 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

public static void main(String args[]){

TestExceptionPropagation2 obj=new TestExceptionPropagation2();

obj.p();

[Link]("normal flow");

Test it Now

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 normal flow 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
performing check up before the code being used.

Syntax of java throws

return_type method_name() throws exception_class_name{

//method code

Which exception should be declared

Ans) checked exception only, because:

unchecked Exception: under your control so correct your code.

error: beyond your control e.g. you 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.

import [Link];

class Testthrows1{

void m()throws IOException{

By Er. RAHAMATULLA (Assistant Professor) Page 35 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

throw new IOException("device error");//checked exception

void n()throws IOException{

m();

void p(){

try{

n();

}catch(Exception e){[Link]("exception handled");}

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

[Link]("normal flow...");

Test it Now

Output:

exception handled

normal flow...

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

There are two cases:

Case1:You caught the exception i.e. handle the exception using try/catch.

Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

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

import [Link].*;

class M{

void method()throws IOException{

throw new IOException("device error");

By Er. RAHAMATULLA (Assistant Professor) Page 36 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

public class Testthrows2{

public static void main(String args[]){

try{

M m=new M();

[Link]();

}catch(Exception e){[Link]("exception handled");}

[Link]("normal flow...");

Test it Now

Output:exception handled

normal flow...

Case2: You declare the exception

A) In case you declare the exception, if exception does not occur, the code will be executed fine.

B) In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.

A)Program if exception does not occur

import [Link].*;

class M{

void method()throws IOException{

[Link]("device operation performed");

class Testthrows3{

public static void main(String args[])throws IOException{//declare exception

M m=new M();

[Link]();

[Link]("normal flow...");

By Er. RAHAMATULLA (Assistant Professor) Page 37 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Test it Now

Output:device operation performed

normal flow...

B)Program if exception occurs

import [Link].*;

class M{

void method()throws IOException{

throw new IOException("device error");

class Testthrows4{

public static void main(String args[])throws IOException{//declare exception

M m=new M();

[Link]();

[Link]("normal flow...");

Test it Now

Output:Runtime Exception

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to declare


explicitly throw an exception. an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method

By Er. RAHAMATULLA (Assistant Professor) Page 38 of 39


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

signature.

5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.

Java throw example

void m(){

throw new ArithmeticException("sorry");

Java throws example

void m()throws ArithmeticException{

//method code

Java throw and throws example

void m()throws ArithmeticException{

throw new ArithmeticException("sorry");

By Er. RAHAMATULLA (Assistant Professor) Page 39 of 39

You might also like