Object oriented programming
Module IV
Programming with JAVA – Overview of Java Language, Classes Objects and Methods, Method
Overloading and Inheritance, Overriding Methods, Final Variables and Methods. Interfaces,
Packages, Multithreaded programming, Managing Errors and Exceptions.
Overview of Java Language
Java’s History
Developed and maintained by Oracle
James Gosling and Sun Microsystems
Aimed at producing an operating environment for networked devices and embedded systems
Java Programming Language Platforms
A Java platform is a particular environment in which Java programming language applications run.
All Java platforms consist of a Java Compiler, Java Virtual Machine (JVM) and an application programming
interface (API).
An API is a collection of software components that you can use to create other software components or
applications.
The API is a library of available java classes, packages and interfaces.
Different Platforms
Java Platform, Standard Edition (J2SE)
Java SE's API provides the core functionality of the Java programming language.
J2SE can be used to develop standalone applications
Java Platform, Enterprise Edition (J2EE)
The Java EE platform provides an API and runtime environment for developing and running large-scale
applications
Java platform Micro Edition (J2ME)
J2ME can be used to develop applications for mobile devices such as cell phones.
JavaFX
JavaFX is a platform for creating rich internet applications
Java Versions
o JDK Alpha and Beta (1995)
o JDK 1.0 (1996)
o JDK 1.1 (1997)
Page 1 CSE , ICET
Object oriented programming
o J2SE 1.2 (1998)
o J2SE 1.3 (2000)
o J2SE 1.4 (2002)
o J2SE 1.5 (2004)
o Java SE 6 (2006)
o Java SE 7 (2011)
o Java SE 8 (2014)
The Compilation Process for Non-Java Programs
The Compilation Process for Java Programs
Java Virtual Machine
How can bytecode be run on any type of computer?
Java Virtual Machine is an interpreter program that converts byte code into object code
. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM).
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
Page 2 CSE , ICET
Object oriented programming
Features of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java Is Simple
Java was designed to be easy for the programmer
For Object-oriented programmers, learning Java will be even easier.
Confusing concepts from C++ are left out of Java or implemented in a cleaner manner. Eg:explicit
pointers, operator overloading etc
Java Is Object-Oriented
Java is inherently object-oriented.
Although many object-oriented languages began strictly as procedural languages, Java was designed
from the start to be object-oriented
The object model in Java is simple and easy to extend
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior
Java Is Distributed
Page 3 CSE , ICET
Object oriented programming
Distributed computing involves several computers working together on a network.
Networking capability is inherently integrated into Java, writing network programs is like sending and
receiving data to and from a file.
Java Is Interpreted
You need an interpreter to run Java programs.
The programs are compiled into the Java Virtual Machine code called byte code.
The byte code is machine-independent and can run on any machine that has a Java interpreter
Byte code is easy to translate into machine code
Java Is Robust
Robust simply means strong. Java uses strong memory management. There is lack of pointers that avoids
security problem.
There is automatic garbage collection in java. There is exception handling and type checking mechanism in
java. All these points make java robust.
Java compilers can detect many errors that would first show up at execution time in other languages.
Java manages memory allocation and deallocation for you
Java has a runtime exception-handling feature to provide programming support for robustness.
Java Is Secure
• Java implements several security mechanisms to protect your system against harm caused by stray
programs.
• Automatic array bounds checking and the lack of manual memory management
• No use of pointers, Exception handling concept etc
Java Is Architecture-Neutral
Write once, run anywhere
With a Java Virtual Machine (JVM), you can write one program that will run on any platform.
Java Is Portable
Because Java is architecture neutral, Java programs are portable. They can be run on any platform without
being recompiled.
Java's Performance
• The execution speed of Java programs improved due to the introduction of Just-In Time
compilation (JIT)
• The Just-In-Time (JIT) compiler improves the performance of Java applications by compiling
bytecodes to machine code at run time
• They can be run on any platform without being recompiled.
Java Is Multithreaded
Page 4 CSE , ICET
Object oriented programming
• Allows you to write programs that do many things simultaneously.
• Multithread programming is smoothly integrated in Java, whereas in other languages you have to call
procedures specific to the operating system to enable multithreading
Java Is Dynamic
Java is considered as Dynamic because of Bytecode[a class file]. A source code written in one platform, the
same code can be executed in any platform [which JDK is installed.]. And it also loads the class files at
runtime
Allow dynamic linking
Classes Objects and Methods
General Form of a class
Data and methods(functions) within the class are called members of the class
class Classname
{
type instance_variable1;
type instance_variable2;
…..
. type instance_variableN;
type methodname1(parameter-list)
{
}
type methodname2(parameter-list)
{
}
.
.
type methodnameN(parameter-list)
{
}
.
.
}
Instance variable in Java
Page 5 CSE , ICET
Object oriented programming
A variable which is created inside the class but outside the method is known as instance variable. Instance
variable doesn't get memory at compile time. It gets memory at run time when object (instance) is created.
That is why, it is known as instance variable.
Example
class Box
{
int breadth;
int height;
int length;
}
Here length,height,breadth are instance variables of class Box
Creating and accessing Object
Classname objectname= new Classname();
Box b=new Box ();
For accessing object we use dot (.) Operator
b.height=100;
Example Program
class Box
{
float length;
float height; // attributesor instance variables of the class
float breadth;
}
class Mainbox
{
public static void main(String args[])
{
Box b=new Box(); // object creation
float v;
b.length=10; // accessing object
b.height=20;
b.breadth=15;
v=b.length*b.height*b.breadth;
System.out.println("Volume is " + v);
Page 6 CSE , ICET
Object oriented programming
}
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
A Java method is a collection of statements that are grouped together to perform an operation.
Now you will learn how to create your own methods with or without return values, invoke a method
with or without parameters, and apply method abstraction in the program design.
The process of method calling is simple. When a program invokes a method, the program control gets
transferred to the called method. This called method then returns control to the caller in two conditions,
when –
the return statement is executed.
it reaches the method ending closing brace.
Syntax
access returntype methodname(parameters)
{
//body of the method }
acess – means public, private or protected
Example
class Box
{ float length;
float height;
float breadth;
void volume()
{
float v;
v= length*height*breadth; // body of the method volume()
System.out.println("The volume is " +v);
}
}
class Mainbox
{
public static void main(String args[])
{
Box b=new Box();
b.length=10;
Page 7 CSE , ICET
Object oriented programming
b.height=20;
b.breadth=30;
b.volume(); // Method calling(caller)
}
}
Using return
The return statement is used to return from a method. That is, it causes program control to transfer back to
the caller of the method
At any time in a method the return statement can be used to cause execution to branch back to the caller
of the method.
class Box
{ float length;
float height;
float breadth;
float volume()
{
float v;
v= length*height*breadth;
return v;
}
class Mainbox
{
public static void main(String args[])
{
Box b=new Box();
float vol;
b.length=10;
b.height=20;
b.breadth=30;
vol=b.volume();
System.out.println(vol);
}
Page 8 CSE , ICET
Object oriented programming
}
Method with parameters
Method parameters make it possible to pass values to the method, which the method can operate on. The
method parameters are declared inside the parentheses after the method name.
class Box
{ float length;
float height;
float breadth;
float volume(double l, double h, double b)
{
length=l;
height=h;
breadth=b;
return length*height*breadth;
}
}
class Mainbox
{
public static void main(String args[])
{
Box b=new Box();
float vol;
vol=b.volume(10,20,30);
System.out.println(vol);
}
}
Overloading Methods
Two or more methods within the same class that share same name.
Parameter declaration must be different
Used to implement compile time polymorphism
Note: - Java uses the type/number of parameters to determine which method to execute
Argument lists could differ in –
1. Number of parameters.
Page 9 CSE , ICET
Object oriented programming
2. Data type of parameters.
3. Sequence of Data type of parameters.
Example 1: Overloading – Different Number of parameters in argument list
class Overload
{
void test()
{
System.out.println("No Parameters!");
}
void test(int a)
{
System.out.println("Parameter is integer"+a);
}
void test(int a,int b)
{
System.out.println("Parameters are integers "+a+ " "+b);
}
}
class Overloadmain
{
public static void main(String args[])
{
Overload o=new Overload();
o.test();
o.test(10);
o.test(10,20);
} }
Example 2: Overloading – Difference in data type of arguments
In this example, method disp() is overloaded based on the data type of arguments – Like example 1 here
also, we have two definition of method disp(), one with char argument and another with int argument.
class DisplayOverload
{
public void disp(char c)
Page 10 CSE , ICET
Object oriented programming
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverload obj = new DisplayOverload();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of arguments – Both the methods have
different sequence of data type in argument list. First method is having argument list as (char, int) and
second is having (int, char). Since the sequence is different, the method can be overloaded without any
issues.
class DisplayOverload
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
Page 11 CSE , ICET
Object oriented programming
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverload obj = new DisplayOverload();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:
I’m the first definition of method disp
I’m the second definition of method disp
Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object.
In this we 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.
The class which inherits the properties of other class is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that we make a new class that derives from an existing class.
Types of Inheritance
Page 12 CSE , ICET
Object oriented programming
Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance.
Single Inheritance
One class(Dog) can inherit the properties of another class(Animal).
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
Page 13 CSE , ICET
Object oriented programming
barking...
eating...
Multilevel Inheritance
you can derive a class from the base class but you can also derive a class from the derived class. This
form of inheritance is known as multilevel inheritance.
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog
{
void weep(){System.out.println("weeping...");}
}
class TestInheritance
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Page 14 CSE , ICET
Object oriented programming
Hierarchical Inheritance
If more than one class is inherited from the base class, it's known as hierarchical inheritance. In
hierarchical inheritance, all features that are common in child classes are included in the base class.
class Animal
{
void eat(){System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal
{
void meow(){System.out.println("meowing...");}
}
class TestInheritance
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Error
}}
Output:
meowing...
eating...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B
classes have same method and you call it from child class object, there will be ambiguity to call method
of A or B class.
Page 15 CSE , ICET
Object oriented programming
Method Overriding
when a method in a subclass has the same name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of that
method defined by the subclass.
Example
class A
{
void callme()
{
System.out.println("This is a method in class A");
}
}
class B extends A
{
void callme()
{
System.out.println("This is a method in class B");
}
}
class C extends A
{
void callme()
{
System.out.println("This is a method in class C");
}
}
class Polymorphism
{
public static void main(String args[])
{
C c1=new C();
c1.callme();
}
Page 16 CSE , ICET
Object oriented programming
}
Dynamic Method dispatch
A call to overridden method is resolved at run time.
Run time polymorphism
Working
When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the time
the call occurs.
Example
class A
{
void callme()
{
System.out.println("This is a method in class A");
}
}
class B extends A
{
void callme()
{
System.out.println("This is a method in class B");
}
}
class C extends A
{
void callme()
{
System.out.println("This is a method in class C");
}
}
class Polymorphism
{
public static void main(String args[])
{
Page 17 CSE , ICET
Object oriented programming
A a1=new A();
B b1=new B();
C c1=new C();
A temp;
temp=a1;
temp.callme();
temp=b1;
temp.callme();
temp=c1;
temp.callme();
}
}
Method Overloading Method Overriding
Parameter must be different and name Both name and parameter must be same.
must be same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code. Increase reusability of code.
Access specifier can be changed. Access specifier most not be more restrictive than
original method
Interfaces
It is similar to classes but they lack instance variables
-their methods are declared without any body(abstract methods)
- all method inside interface must be abstract methods
One class can implement any number of interfaces
- Interface provides 100% abstraction
- Also support the concept of multiple inheritance
In this example, Printable interface has only one method, its implementation is provided in the A class.
interface Printable
{
void print();
Page 18 CSE , ICET
Object oriented programming
}
class A implements printable
{
public void print()
{System.out.println("Hello");}
}
class Interface1
{
public static void main(String args[])
{
A obj = new A();
obj.print();
}
}
Output:
Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
interface Printable
{
void print();
}
interface Showable
{
Page 19 CSE , ICET
Object oriented programming
void show();
}
class A implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
}
class TestInterface1
{
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
Implementing interface - syntax
access class classname [implements interface1,[interface2],….]
{
//class-body
}
Note:-
More than one interfaces can be used.
Type signature of method in class must match with the method declaration in interface
Interfaces can be extended
One interface can inherit other
interface A
{
void meth1();
void meth2();
}
Page 20 CSE , ICET
Object oriented programming
// b now include meth1(),meth2() – it adds meth3()
interface B extends A
{
void meth3();
}
class Example implements B
{
public void meth1()
{
System.out.println("method1");
}
public void meth2()
{
System.out.println("method2");
}
public void meth3()
{
System.out.println("method3");
}
}
class Inheritance
{
public static void main(String args[])
{
Example e=new Example();
e.meth1();
e.meth2();
e.meth3();
}
}
Java Interface Example
In this example, Drawable interface has only one method. Its implementation is provided by Rectangle
and Circle classes.
interface Drawable
Page 21 CSE , ICET
Object oriented programming
{
void draw();
}
class Rectangle implements Drawable
{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable
{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}}
Output:
drawing circle
Packages
Packages are containers for classes
Packages manage namespaces
Namespaces allow to group entities like classes, objects and functions under a name
Classes inside a package cannot be accessed by code outside that package
Package in java can be categorized in two form, built-in package and user-defined package.
built-in package
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Page 22 CSE , ICET
Object oriented programming
import java.io.*;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
user defined package
syntax for user defined package
package pkg;
pkg - can be any name
o First statement in java source code
o If no package is specified, the class name is put into default package without any name
o Class files must be stored in the same directory of the package
Hierarchy of packages
package pkg1.pkg2.pkg3……..;
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Importing packages
Page 23 CSE , ICET
Object oriented programming
import pkg1.pkg2.classname;
import pkg1.*;
All standard classes in java are under the package java.
If a programmer need these classes he can import those
Eg:- import java.io.*;
Final variables and methods
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but it can't be
changed because final variable once assigned a value can never be changed.
class Bike
{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // we cannot change the value of final variable
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}//end of class
Output: Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike
Page 24 CSE , ICET
Object oriented programming
{
final void run()
{System.out.println("running");} // final method
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
We cannot write run() in super class and sub class because run is a final method.
Blank final variable
A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error (Error: variable MAX_VALUE might not have been initialized).
This is how a blank final variable is used in a class:
class Demo{
final int MAX_VALUE; //Blank final variable
Demo(){
MAX_VALUE=100; //It must be initialized in constructor
}
void myMethod(){
System.out.println(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod(); } }
Output:
100
Page 25 CSE , ICET
Object oriented programming
Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads.
It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Multi-Thread Programming
A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread
A thread is an independent path of execution within a program.
Every thread in Java is created and controlled by the java.lang.Thread class.
Note: - Most of the programs are single threaded
Thread priorities
Java assigns to each thread a priority
Thread priorities are integers that specify the relative priority of one thread to another.
A thread’s priority is used to decide when to switch from one running thread to the next. This is called a
context switch
Life cycle of a Thread (Thread States)
A thread can be in one of the five states
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Page 26 CSE , ICET
Object oriented programming
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
Java Thread Example by extending Thread class
class Multi extends Thread
{
public void run()
Page 27 CSE , ICET
Object oriented programming
{
System.out.println("thread is running...");
} }
class Example
{
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
When we call start () ,control moves to its run()
2) Java Thread Example by implementing Runnable interface
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
} }
class Example
{
public static void main(String args[])
{
Multi m1=new Multi();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread object. So you
need to explicitly create Thread class object. We are passing the object of your class that implements
Page 28 CSE , ICET
Object oriented programming
Runnable so that your class run() method may execute.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Example of sleep method in java
1. class Test extends Thread
2. {
3. public void run()
4. {
5. for(int i=1;i<5;i++)
6. {
7. System.out.println(i);
8.
9. Thread.sleep(500);
10. }
11. }
12. }
13. class Example
14. {
15. public static void main(String args[])
16. {
17. Test t1=new Test ();
18. Test t2=new Test ();
19. t1.start();
20. t2.start();
21. }
22. }
Output:
1
1
2
2
3
Page 29 CSE , ICET
Object oriented programming
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the
thread shedular picks up another thread and so on.
Naming Thread
The Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread
1. class Test extends Thread
2. {
3. public void run(){
4. System.out.println("running...");
5. } }
6. class Example
7. {
8. public static void main(String args[])
9. {
10. Test t1=new Test();
11. Test t2=new Test();
12. System.out.println("Name of t1:"+t1.getName());
13. System.out.println("Name of t2:"+t2.getName());
14.
15. t1.start();
16. t2.start();
17.
18. t1.setName("Sonoo Jaiswal");
19. System.out.println("After changing name of t1:"+t1.getName());
20. }
21. }
Page 30 CSE , ICET
Object oriented programming
Test it Now
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority.
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.
Example of priority of a Thread:
1. class Test extends Thread
2. {
3. public void run()
4. {
5. System.out.println("running thread name is:"+Thread.currentThread().getName());
6. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
7. } }
8. class Example
9. {
10. public static void main(String args[]){
11. Test m1=new Test();
12. Test m2=new Test();
13. m1.setPriority(Thread.MIN_PRIORITY);
Page 31 CSE , ICET
Object oriented programming
14. m2.setPriority(Thread.MAX_PRIORITY);
15. m1.start();
16. m2.start();
17. }
18. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime errors
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.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote
etc.
Hierarchy of Java Exception classes
Types of Exception
Page 32 CSE , ICET
Object oriented programming
There are mainly two types of exceptions: checked and unchecked
Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
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.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
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=Integer.parseInt(s);//NumberFormatException
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.
Page 33 CSE , ICET
Object oriented programming
try
catch
finally
throw
throws
General form of exception handling block
try
{
block of code to monitor for errors
}
catch(Exceptiontype1 objname)
{
Handler for exception type1
}
catch(Exceptiontype2 objname)
{
Handler for exception type2
}
……..
finally
{
// block of code to be executed before try block ends
}
Using try catch
class Try1
{
public static void main(String args[])
{
int a,d;
try
{
d=0;
a=42/d;
System.out.println("a=" +a);
Page 34 CSE , ICET
Object oriented programming
}
catch(ArithmeticException e )
{
System.out.println(e);
}
System.out.println("This is after try catch");
}
}
Multiple Catch
When more than one exception could be raised from a single piece of code
Specify more than one catch block
Each catch statement will be inspected in order
The first matching catch is selected and rest is bypassed
class Try1
{
public static void main(String args[])
{
int n;
try
{
Scnner s=new Scanner(System.in);
n= s.nextInt();
int a=50/n;
int c[]={1};
c[42]=99;
Page 35 CSE , ICET
Object oriented programming
}
catch(ArithmeticException ae )
{
System.out.println(ae);
}
catch(ArrayIndexOutOfBoundsException arr )
{
System.out.println(arr);
}
System.out.println("This is after try catch");
}
}
Nested try statements
class Try1
{
public static void main(String args[])
{
try
{
Scnner s=new Scanner(System.in);
n= s.nextInt();
int a=50/n;
try
{
int c[]={1};
c[42]=99;
}
}
catch(ArrayIndexOutOfBoundsException arr)
{
System.out.println(arr);
}
catch(ArithmeticException ae )
Page 36 CSE , ICET
Object oriented programming
{
System.out.println(ae);
}
}
}
finally
Finally is a block of statements that will be executed immediately after try catch block
Example
class Test
{
void a()
{
try
{
System.out.println("Inside A");
}
finally
{
System.out.println("Inside A's Finally");
}
}
}
class Example
{
public static void main(String args[])
{
Test t= new Test();
t.a();
}
}
throw
You have only been catching exceptions that are thrown by the Java run time system. However, it is
possible for our pgm to thrown an exception explicitly.
Syntax: throw throwableInstance;
Page 37 CSE , ICET
Object oriented programming
Example
class Try1
{
try
{
void validate(int age)
{
If(age<18)
throw new Arithmetic Exception(“not valid”);
else
System.out.println(“voting permitted”);
}
}
catch (Arithmetic Exception n)
{
System.out.println(n);
}
System.out.println(“After try/catch block”);
}
class Example
{
public static void main(String args[])
validate(13);
}
}
OUTPUT
Java.lang.ArithmeticException:not valid
After try/catch block
throws
- If a method is capable of generating an exception that it cannot handle
- Include a throws clause in the method’s declaration
- Can notify the caller about possible exceptions
type method-name(parameter list) throws exception list
{
Page 38 CSE , ICET
Object oriented programming
// body of the method
}
o Exception list is a comma separated list
class Try1
{
try
{
void validate(int age) throws ArithmeticException
{
if(age<18)
throw new Arithmetic Exception(“not valid”);
else
System.out.println(“voting permitted”);
}
}
catch (Arithmetic Exception n)
{
System.out.println(n);
}
System.out.println(“After try/catch block”);
}
class Example
{
public static void main(String args[])
validate(13);
}
}
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
2) Checked exception cannot be Checked exception can be propagated with
propagated using throw only. throws.
Page 39 CSE , ICET
Object oriented programming
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 signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Page 40 CSE , ICET