0% found this document useful (0 votes)
13 views48 pages

Java Unit -III

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views48 pages

Java Unit -III

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 48

R 20 OOPS THROUGH JAVA

UNIT – III
EXCEPTION HANDLING
EXCEPTION HANDLING IN JAVA
An exception in java programming is an abnormal situation that is raised during
the program execution. In simple words, an exception is a problem that arises at the
time of program execution.

When an exception occurs, it disrupts the program execution flow. When an


exception occurs, the program execution gets terminated, and the system generates
an error. We use the exception handling mechanism to avoid abnormal termination
of program execution.

Java programming language has a very powerful and efficient exception handling
mechanism with a large number of built-in classes to handle most of the exception
automatically. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException,IOException, SQLException, RemoteException,etc.

Reasons for Exception Occurrence:


Several reasons lead to the occurrence of an exception. A few of them are as follows.

 When we try to open a file that does not exist may lead to anexception.
 When the user enters invalid input data, it may lead to anexception.
 Whenanetworkconnectionhaslostduringtheprogramexecutionmayleadto
anexception.
 Whenwetrytoaccessthememorybeyondtheallocatedrangemayleadtoan
exception.
 The physical device problems may also lead to anexception.

Syeda Sumaiya Afreen Page 1


R 20 OOPS THROUGH JAVA

Advantage:
The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the application
that is why we use exception handling.
 Separating Error-Handling code from “regular” business logiccode
 Propagating errors up the callstack
 Grouping and differentiating errortypes

For Example:
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 your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
Hierarchy of Java Exception classes:

Java programming language has the following class hierarchy to support the exception handling

mechanism:The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses : Exception and Error.

Syeda Sumaiya Afreen Page 2


R 20 OOPS THROUGH JAVA

Syeda Sumaiya Afreen Page 3


R 20 OOPS THROUGH JAVA
Types of Java Exceptions :
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:
1. CheckedException
2. UncheckedException
3. Error

1) CheckedException

The checked exception is an exception that is checked by the compiler during the
compilation process to confirm whether the exception is handled by the
programmer or not. If it is not handled, the compiler displays a compilation error
using built-in classes.

The checked exceptions are generally caused by faults outside of the code itself
like missing resources, networking errors, and problems with threads come to
mind.
The classes which directly inherit Throwable class except Runtime Exception and

Error are known as checked exceptions e.g. IOException, SQLException etc.

Checked exceptions are checked at compile-time.

The following are a few built-in classes used to handle checked exceptions in java.

 IOException
 FileNotFoundException

 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
 UnknownHostException

Syeda Sumaiya Afreen Page 4


R 20 OOPS THROUGH JAVA
In the exception class hierarchy, the checked exception classes are the direct children
of the Exception class. The checked exception is also known as a compile-time exception.

2) UncheckedException :

The unchecked exception is an exception that occurs at the time of program execution.
The unchecked exceptions are not caught by the compiler at the time ofcompilation.

The unchecked exceptions are generally caused due to bugs such as logic errors,
improper use of resources, etc.

The following are a few built-in classes used to handle unchecked exceptions in java.

 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
In the exception class hierarchy, the unchecked exception classes are the children
of RuntimeException class, which is a child class of Exception class. The unchecked exception
is also known as a runtime exception

The classes which inherit RuntimeException are known as unchecked exceptions

e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.,

Unchecked exceptions are not checked at compile-time,but they are checked at runtime.

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

Syeda Sumaiya Afreen Page 5


R 20 OOPS THROUGH JAVA
Java Exception Keywords

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

Keyword Descripti
on
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The"throws"keywordisusedtodeclareexceptions.Itdoesn'tthrowanexception.Itspecifi
es that there may occur an exception in the method. It is always used with
methodsignature.

General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }

where:
1) try { … } is the block of code to monitor forexceptions
2) catch(Exception ex) { … } is exception handler for the exceptionException
3) finally { … } is the block of code to execute before the try blockends

Example:
1. public classJavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raiseexception
5. intdata=100/0;
6. }catch(ArithmeticException e) //catch(Exceptione)
Syeda Sumaiya Afreen Page 6
R 20 OOPS THROUGH JAVA
7. {System.out.println(e);}
8. //rest code of theprogram
9. System.out.println("rest of the
code...");
10. }}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Some scenarios where unchecked exceptions may occur. they are as follows:

1) A scenario where ArithmeticExceptionoccurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerExceptionoccurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

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

3) A scenario where NumberFormatExceptionoccurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsExceptionoccurs


If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shownbelow:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Syeda Sumaiya Afreen Page 7


R 20 OOPS THROUGH JAVA

TERMINATION VS. RESUMPTION

Exception Models in Java


In java, there are two exception models. Java programming language has two
models of exception handling. The exception models that java supports are as
follows.

 TerminationModel
 ResumptiveModel

Let's look into details of each exception model.

1. Termination Model

There are two basic models in exception-handling theory. In termination (which is what
C++supports)you assume the error is so critical there’s no way to get back to where the
exception occurred. Whoever threw the exception decided there was no way to salvage the
situation, and they don’t want to comeback.

2. ResumptiveModel

The alternative is called resumption. It means the exception handler is expected to do


something to rectify the situation, and then the faulting function is retried, presuming success
the second time. If you want resumption, you still hope to continue execution after the
exception is handled, so your exception is more like a function call – which is how you should
set up situations in C++ where you want resumption-like behavior (that is, don’t throw an
exception; call a function that fixes the problem). Alternatively, place your try block inside a
while loop that keeps reentering the try block until the result is satisfactory.

Historically, programmers using operating systems that supported resumptive exception


handling eventually ended up using termination-like code and skipping resumption. So
although resumption sounds attractive at first,it seems it isn’t quite so useful in practice. One
reason may be the distance that can occur between the exception and its handler; it’s one thing
to terminate to a handler that’s far away, but to jump to that handler and then back again may
be too conceptually difficult for large systems where the exception can be generated from
manypoints.

Syeda Sumaiya Afreen Page 8


R 20 OOPS THROUGH JAVA

UNCAUGHT EXCEPTIONS IN JAVA


In java, assume that, if we do not handle the exceptions in a program. In this case,
when an exception occurs in a particular function, then Java prints a exception
message with the help of uncaught exception handler.

The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.

Java programming language has a very stronger exception handling mechanism. It


allow us to handle the exception use the keywords like try, catch, finally, throw,
and throws.

When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates thethread.

The Division by zero exception is one of the example for uncaught exceptions.
Look at the following code.

Example :

importjava.util.Scanner;

public class UncaughtExceptionExample{

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.println("Enter the a and b values: ");

int a =read.nextInt();

int b = read.nextInt();
Syeda Sumaiya Afreen Page 9
R 20 OOPS THROUGH JAVA
Int c = a /b;

System.out.println(a + "/" + b +" = " + c);


}
}
In the above example code, we are not used try and catch blocks, but when the value of b
is zero the division by zero exception occurs and it caught by the default exception handler.

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 of 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: Java try-catch


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

Syntax: try-finally block


1. try{
2. //code that may throw anexception
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 providesa default exception handler that performs the followingtasks:
Syeda Sumaiya Afreen Page 10
R 20 OOPS THROUGH JAVA

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exceptionoccurred).
o Causes the program toterminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.

Syeda Sumaiya Afreen Page 11


R 20 OOPS THROUGH JAVA
Example:
Problem without exception handling
1. public class
TryCatchExample1 {

2.public static void


main(String[] args) {

3. int data=50/0; //may throw


exception

4.System.out.println("rest of the
code");

5.}}

Output:
Exception in thread "main" java.lang.ArithmeticException: /byzero
As displayed in the above example, the rest of the code is not executed (in such case, the rest
of the code statement is notprinted).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling


1. public class TryCatchExample2{
2. public static void main(String[] args){
3. try
4. {
5. int data=50/0; //may throwexception
6. }

7. //handling theexception
8. catch(ArithmeticExceptione)
9. {
10. System.out.println(e);
11. }
12. System.out.println("rest of the
code"); 13. }}

Syeda Sumaiya Afreen Page 12


R 20 OOPS THROUGH JAVA
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.

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, usejavamulti- catchblock.

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

Example:
1. public class MultipleCatchBlock1{
2. public static void main(String[] args){
3. try{
4. int a[]=newint[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e)
8. {
9. System.out.println("Arithmetic Exceptionoccurs");
10. }
11. catch(ArrayIndexOutOfBoundsExceptione)
12. {
13. System.out.println("ArrayIndexOutOfBounds Exceptionoccurs");
14. }
15. catch(Exceptione)
16. {
17. System.out.println("Parent Exceptionoccurs");
18. }

19. System.out.println("rest of the


code"); 20. }}

Syeda Sumaiya Afreen Page 13


R 20 OOPS THROUGH JAVA
Output:
Arithmetic Exception occurs
rest of the code

NESTED TRY BLOCK

Thetryblockwithinatryblockisknownasnestedtryblockinjava.Sometimesasituationmayarisewhere
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 benested.

Syntax:
1. ....
2. try
3. {
4. statement1;
5. statement2;
6. try
7. {
8. statement1;
9. statement2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....

Example:
1. classExcep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to
divide"); 6. int b=39/0;
7. }catch(ArithmeticException
e){System.out.println(e);} 8.
9. try{
10. int a[]=newint[5];
Syeda Sumaiya Afreen Page 14
R 20 OOPS THROUGH JAVA
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsExceptione){System.out.println(e);}
13. System.out.println("other statement);
14. }catch(Exception e){System.out.println("handeled");}
15. System.out.println("normal
flow.."); 16. }}

Output:

going to divide
java.lang.ArithmeticException: /
by zero
java.lang.ArrayIndexOutOfBoundsE
xception: 5 other statement
normal flow..

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.
The syntax of java throw keyword is given below.
throw exception;

example of throw IOException.


throw new IOException("sorry device error”);

In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
1. public classTestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("notvalid");
5. else
6. System.out.println("welcome to
vote"); 7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the
code..."); 11. }}
Syeda Sumaiya Afreen Page 15
R 20 OOPS THROUGH JAVA

Output:
Exception in thread main java.lang.ArithmeticException:notvalid

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.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

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

Output:exception handled
normal flow...

Syeda Sumaiya Afreen Page 16


R 20 OOPS THROUGH JAVA
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).

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

Output: Compile Time Error

THROWS KEYWORD

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that the their reman occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can bemaintained.

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.

Syeda Sumaiya Afreen Page 17


R 20 OOPS THROUGH JAVA
Syntax:
1. return_type method_name() throwsexception_class_name{
2. //methodcode
3. }

Checked exceptions only declared because:


o unchecked Exception: under your control so correct your code.
o error: beyond your control e.g. you are unable to do anything if there occurs Virtual
Machine Error orStackOverflowError.

Advantages:
o Now Checked Exception can be propagated (forwarded in callstack).
o It provides information to the caller of the method about theexception.
the example of java throws clause which describes that checked exceptions can be propagated by
throws keyword.
1. import java.io.IOException;
2. classTestthrows1{
3. void m()throwsIOException{
4. throw new IOException("device error");//checked
exception 5. }
6. void n()throws
IOException{ 7.
m();
8. }
9. voidp(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exceptionhandled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=newTestthrows1();
16. obj.p();
17. System.out.println("normal
flow..."); 18. }}

Output:
exception handled
normal flow...

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

Syeda Sumaiya Afreen Page 18


R 20 OOPS THROUGH JAVA

There are two cases:


1. Case1: You caught the exception i.e. handle the exception usingtry/catch.
2. Case2: You declare the exception i.e. specifying throws with themethod.

Case1: You handle the exception


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

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

Output:exception handled
normal flow...

Case2: You declare the exception


o A)In case you declare the exception, if exception does not occur, the code will be executedfine.
o B)In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle theexception.

A) Program if exception does notoccur


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

Output:device operation performed


normal flow...

Syeda Sumaiya Afreen Page 19


R 20 OOPS THROUGH JAVA

B) Program if exceptionoccurs
1. import java.io.*;
2. classM{
3. void method()throwsIOException{
4. throw new IOException("device
error"); 5. }}
6. classTestthrows4{
7. public static void main(String args[])throws IOException{//declare exception
8. M m=newM();
9. m.method();
10. System.out.println("normal
flow..."); 11. }}

Output:

Exception in thread "main" java.io.IOException:


device error at
M.method(Testthrows4.java:4)

at Testthrows4.main(Testthrows4.java:10)

FINALLY BLOCK
Java finally block is a block that is used to execute important code such as closing connection,
stream
etc.Javafinallyblockisalwaysexecutedwhetherexceptionishandledornot.Javafinallyblockfollowst
ry or catchblock.

Syeda Sumaiya Afreen Page 20


R 20 OOPS THROUGH JAVA

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

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

Case 1

Let's see the java finally example where exception doesn't occur.
1. classTestFinallyBlock{
2. public static void main(String args[]){
3. try{

4. intdata=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerExceptione){System.out.println(e);}
8. finally{System.out.println("finally block is alwaysexecuted");}
9. System.out.println("rest of the
code..."); 10. }}

Output:5
finally block is always executed
rest of the code...

Case 2
Let's see the java finally example where exception occurs and not handled.
1. classTestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. intdata=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerExceptione){System.out.println(e);}
8. finally{System.out.println("finally block is alwaysexecuted");}
9. System.out.println("rest of the
code..."); 10. }}

Output:finally block is always executed


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

Case 3
Syeda Sumaiya Afreen Page 21
R 20 OOPS THROUGH JAVA
Let's see the java finally example where exception occurs and handled.
1. public classTestFinallyBlock2{
2. public static void main(Stringargs[]){
3. try{
4. intdata=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is alwaysexecuted");}
9. System.out.println("rest of the
code..."); 10. }}

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


finally block is always executed
rest of the code...

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 program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

JAVA BUILT IN EXCEPTIONS


Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.

Java defines several other types of exceptions that relate to its various class libraries.
Following is the list of Java Unchecked RuntimeException.

Syeda Sumaiya Afreen Page 22


R 20 OOPS THROUGH JAVA

Exception Meaning

Syeda Sumaiya Afreen Page 23


R 20
OOPS THROUGH JAVA

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Meaning
ClassNotFoundException Class not found
CloneNotSupportedException Attempt to clone an object that doesn't implement the Cloneable
interface
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an object of an abstract class or interface
InterruptedException One thread has been interrupted by another thread
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method doesn't exist
ReflectiveOperationException Superclass of reflection-related exceptions

Creating Own Exceptions in Java

The Java programming language allow us to create our own exception


classes which are basically subclasses built-in class Exception. To create
our own exception class simply create a class as a subclass of built-in
Exception class.We may create constructor in the user-defined exception
class and pass a string to Exception class constructor using super(). We can
use getMessage()method to access the string.

If you are creating your own Exception that is known as custom exception or user-
defined exception. Java custom exceptions are used to customize the exception
according to user need.

Syeda Sumaiya Afreen


Page 24
R 20
OOPS THROUGH JAVA

By the help of custom exception, you can have


your own exception and message.

class InvalidAgeException extendsException{


1. InvalidAgeException(String s){
2. super(s);
4. }}

1. classTestCustomException1{
2. static void validate(int age)throwsInvalidAgeException{
3. if(age<18)
4. throw new InvalidAgeException("notvalid");
5. else
6. System.out
.println("welcome
to vote");
}
8. public static void main(String args[]){
9. try{
10. validate(13);
11. }catch(Exception m){System.out.println("Exception occured:"+m);}
12. System.out.
println("rest of the
code..."); 13. }}

Output:Exception occured:
InvalidAgeException:not
valid rest of the code...

MULTITHREADING
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a


shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
Syeda Sumaiya Afreen
Page 25
R 20
OOPS THROUGH JAVA

process.

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

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


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

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each
process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for
saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
Syeda Sumaiya Afreen
Page 26
R 20
OOPS THROUGH JAVA

Process-based multitasking Thread-based multitasking

In this process is the smallest unit. In this thread is the smallest


unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for Threads share same


each. address space.

Process never gain access over idle time of CPU. Thread gain access over
idle time

of CPU.

Inter process communication is expensive. Inter thread


communication is not

expensive.

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


separate path of execution. Threads are independent. If there occurs
exception in one thread, it doesn't affect other threads. It uses a shared
memory area.

Syeda Sumaiya Afreen


Page 27
R 20
OOPS THROUGH JAVA

As shown in the above figure, a thread is executed inside the process. There
is context-switching between the threads. There can be multiple processes
inside the OS, and one process can have multiple threads.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable
interface.

LIFE CYCLE OF A THREAD (THREAD STATES)


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

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
1. New
2. Runnable
3. Running

Syeda Sumaiya Afreen


Page 28
R 20
OOPS THROUGH JAVA

4. Non-Runnable (Blocked)
5. Terminated

1) New
The thread is in new state if you create an instance of Thread class but before
the invocation 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.

Syeda Sumaiya Afreen


Page 29
R 20
OOPS THROUGH JAVA

CREATING THREADS

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform


operations on a thread. Thread class extends Object class and implements
Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the
run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
4. public void join(): waits for a thread to die.

Syeda Sumaiya Afreen


Page 30
R 20
OOPS THROUGH JAVA

5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently
executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended
thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

Example:

Syeda Sumaiya Afreen


Page 31
R 20
OOPS THROUGH JAVA

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.
println("thread
is running...");
4. }

Output:thread is running...

Runnable interface:

The Runnable interface should be implemented by any class whose instances


are intended to be executed by a thread. Runnable interface have only one
method named run().

public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will
run.
Example:

4. class Multi3 implements Runnable{

Syeda Sumaiya Afreen


Page 32
R 20
OOPS THROUGH JAVA

5. public void run(){


6. System.out.
println("thread
is running...");
4. }
7. public static void main(String args[]){
8. Multi3 m1=new Multi3();
9. Thread t1 =new Thread(m1);
10. t1.start();
9. } }

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 Runnable so that your
class run() method may execute.

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 (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.

Thread class defines following 3 constants:


1. public static int MIN_PRIORITY

Syeda Sumaiya Afreen


Page 33
R 20
OOPS THROUGH JAVA

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.

Get and Set Thread Priority:


1. public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
2. public final void setPriority(int newPriority):
java.lang.Thread.setPriority() method changes the priority of thread to
the value newPriority. This method throws IllegalArgumentException
if value of parameter newPriority goes beyond minimum(1) and
maximum(10) limit.

Example :

class SampleThread extends Thread{

public void run(){

System.out.println("Inside SampleThread");

System.out.println("Current Thread Name: " +


Thread.currentThread().getName());
System.out.println("Current Thread Priority: " +
Thread.currentThread().getPriority());
}
public class My_Thread_Test{

Syeda Sumaiya Afreen


Page 34
R 20
OOPS THROUGH JAVA

public static void main(String[] args) {

SampleThread threadObject1 = new SampleThread();


SampleThreadthreadObject2 = new SampleThread();
threadObject1.setName("first");

threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();

Output:
Inside Sample thread
Current thread Name:first
Current thread Name:second
Current thread Priority: 4
Current thread Priority: 10

SYNCHRONIZATION

The java programming language supports multithreading. The problem of


shared resources occurs when two or more threads get execute at the same time. In
such a situation, we need some way to ensure that the shared resource will be
Syeda Sumaiya Afreen
Page 35
R 20
OOPS THROUGH JAVA

accessed by only one thread at a time, and this is performed by using the concept
called synchronization.

Synchronization in java is the capability to control the access of


multiple threads to any shared resource. Java Synchronization is better
option where we want to allow only one thread to access the shared resource.

Advantage:

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

In java, the synchronization is achieved using the following concepts.

 MutualExclusion
 Inter threadcommunication

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one
another while they accessing the shared resource. In java, mutual exclusion is
achieved using the following concepts.

Syeda Sumaiya Afreen


Page 36
R 20
OOPS THROUGH JAVA

 Synchronized method
 Synchronized block

1.Synchronised Method :

When a method created using a synchronized keyword, it allows only one object to
access it at a time. When an object calls a synchronized method, it put a lock on that
method so that other objects or thread that are trying to call the same method must
wait, until the lock is released. Once the lock is released on the shared resource, one
of the threads among the waiting threads will be allocated to the shared resource.

In the above image, initially the thread-1 is accessing the synchronized method and
other threads (thread-2, thread-3, and thread-4) are waiting for the resource
(synchronizedmethod).Whenthread-1completesittask,thenoneofthethreadsthat are
waiting is allocated with the synchronized method, in the above it isthread-3.

Syeda Sumaiya Afreen


Page 37
R 20
OOPS THROUGH JAVA

Lock:
Synchronization is built around an internal entity known as the lock or
monitor. Every object has an lock associated with it. By convention, a thread
that needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done with
them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Without Synchronization
there is no synchronization, so output is inconsistent. Let's see the example:
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Excepti
on
e){System.out.print
ln(e);} 8. } } }
9. class MyThread1 extends Thread{
10. Table t;
11. MyThread1(Table t){
12. this.t=t;
13. }
14. public void run(){
15. t.printTable(5);
16. } }
17. class MyThread2 extends Thread{
18. Table t;
19. MyThread2(Table t){
20. this.t=t;
21. }
22. public void run(){
23. t.printTable(100);

Syeda Sumaiya Afreen


Page 38
R 20
OOPS THROUGH JAVA

24. } }
25. class TestSynchronization1{
26. public static void main(String args[]){
27. Table obj = new Table();//only one object
28. MyThread1 t1=new MyThread1(obj);
29. MyThread2 t2=new MyThread2(obj);
30. t1.start();
31. t2.start();
32. } }

Output: 5

100

10

200

15

300

20

400

25

500

synchronized method:

If you declare any method as synchronized, it is known as synchronized method.


Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock


for that object and releases it when the thread completes its task.

1. //example of java synchronized method

2. class Table{
Syeda Sumaiya Afreen
Page 39
R 20
OOPS THROUGH JAVA

3. synchronized void printTable(int n){//synchronized method

4. for(int i=1;i<=5;i++){

5. System.out.println(n*i);

6. try{

7. Thread.sleep(400);

8. }catch(Exception e){System.out.println(e);}

9. }}}

10. class MyThread1 extends Thread{

11.Table t;

12.MyThread1(Table t){

13.this.t=t;

14.}

15.public void run(){

16.t.printTable(5);

17.} }

18. class MyThread2 extends Thread{

19. Table t;

20.MyThread2(Table t){

21.this.t=t;

22.}

23.public void run(){

24.t.printTable(100);
Syeda Sumaiya Afreen
Page 40
R 20
OOPS THROUGH JAVA

25.} }

26. public class TestSynchronization2{

27.public static void main(String args[]){

28.Table obj = new Table();//only one object

29.MyThread1 t1=new MyThread1(obj);

30.MyThread2 t2=new MyThread2(obj);

31.t1.start();

32.t2.start();

33.} }

Output: 5

10

15

20

25

100

200

300

400

500

Synchronized Block
Synchronized block can be used to perform synchronization on any specific
resource of the method. Suppose you have 50 lines of code in your method,
Syeda Sumaiya Afreen
Page 41
R 20
OOPS THROUGH JAVA

but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work
same as the synchronized method.

Points to remember
o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax
1. synchronized (object reference expression) {
2. //code block
3. }

Example:

1. class Table{

2. void printTable(int n){

3. synchronized(this){//synchronized block

4. for(int i=1;i<=5;i++){

5. System.out.println(n*i);

6. try{

7. Thread.sleep(400);

8. }catch(Exception e){System.out.println(e);} 9. }

10. }

11. }//end of the method

12. }

13. class MyThread1 extends Thread{

14. Table t;

Syeda Sumaiya Afreen


Page 42
R 20
OOPS THROUGH JAVA

15. MyThread1(Table t){

16. this.t=t;

17. }

18. public void run(){

19. t.printTable(5); 20. } }

21. class MyThread2 extends Thread{

22. Table t;

23. MyThread2(Table t){

24. this.t=t;

25. }

26. public void run(){

27. t.printTable(100); 28. } }

29. public class TestSynchronizedBlock1{

30. public static void main(String args[]){

31. Table obj = new Table();//only one object

32. MyThread1 t1=new MyThread1(obj);

33. MyThread2 t2=new MyThread2(obj);

34. t1.start();

35. t2.start();

36. }}

Syeda Sumaiya Afreen


Page 43
R 20
OOPS THROUGH JAVA

INTER-THREAD COMMUNICATION

Inter-thread communication or Co-operation is all about allowing


synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread


is paused running in its critical section and another thread is allowed to enter
(or lock) in the same critical section to be executed. It is implemented by
following methods of Object class:
o wait()
o notify()
o notifyAll()

1.wait() method
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception.

Method Description

Syeda Sumaiya Afreen


Page 44
R 20
OOPS THROUGH JAVA

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.

2.notify() method
Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()

3.notifyAll() method
Wakes up all threads that are waiting
on this object's monitor.
Syntax:
public final void notifyAll()

Points:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the
Syeda Sumaiya Afreen
Page 45
R 20
OOPS THROUGH JAVA

object. Otherwise it releases the lock and exits.


4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.

Note: wait(), notify() and notifyAll() methods are defined in Object


class not Thread class because they are related to lock and object has a
lock.

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.

Example:

1. class Customer{

2. int amount=10000;

3. synchronized void withdraw(int amount){

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

5. if(this.amount<amount){

6. System.out.println("Less balance; waiting for deposit...");


Syeda Sumaiya Afreen
Page 46
R 20
OOPS THROUGH JAVA

7. try{wait();}catch(Exception e){}

8. }

9. this.amount-=amount;

10. System.out.println("withdraw completed...");

11. }

12. synchronized void deposit(int amount){

13. System.out.println("going to deposit...");

14. this.amount+=amount;

15. System.out.println("deposit completed... ");

16. notify();

17. } }

18. class Test{

19. public static void main(String args[]){

20. final Customer c=new Customer();

21. new Thread(){

22. public void run(){c.withdraw(15000);}

23. }.start();

24. new Thread(){

25. public void run(){c.deposit(10000);}

26. }.start(); 27. }}

Output: going to withdraw...

Less balance; waiting for deposit... going to deposit...


Syeda Sumaiya Afreen
Page 47
R 20
OOPS THROUGH JAVA

deposit completed... withdraw completed

Syeda Sumaiya Afreen


Page 48

You might also like