0% found this document useful (0 votes)
19 views35 pages

Ii Ii JP Unit-3

The document provides an overview of exception handling in Java, detailing its importance in managing runtime errors, bugs, and memory leaks. It explains the types of errors (compile-time and runtime), the classification of exceptions (checked and unchecked), and the use of keywords such as try, catch, and finally for handling exceptions. Additionally, it includes examples of Java programs demonstrating exception handling techniques, including multiple catch blocks and nested try-catch structures.

Uploaded by

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

Ii Ii JP Unit-3

The document provides an overview of exception handling in Java, detailing its importance in managing runtime errors, bugs, and memory leaks. It explains the types of errors (compile-time and runtime), the classification of exceptions (checked and unchecked), and the use of keywords such as try, catch, and finally for handling exceptions. Additionally, it includes examples of Java programs demonstrating exception handling techniques, including multiple catch blocks and nested try-catch structures.

Uploaded by

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

Sub: Java Programming

JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES


RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Exception Handling
1. A program or application or project which overcomes 3 factors called as successful program or
project. Those are:
a. Resource not found errors at Runtime & logical errors of program at runtime
b. Bugs of the program
c. Memory leaks and inceptions for the programs
2. Java is Robust, which provides solution for the above 3 problems to make java programs
successful.
The Solution given by java is
a. Exception Handling: for resource errors and logical errors at runtime.
b. Java Debugging / Java unit testing for bugs
c. Inbuilt automatic garbage collector mechanism for memory leaks, insufficient memory.
What is Error? Types of Errors?
An Error is a syntactical mistake within the program code, which leads termination of program
compilation.
Errors are 2 types
1. Compile time errors
2. Run-time errors
Compile time error:
 Errors which occur at compile time are known as compile time errors.
Ex: Syntactical Errors, Semantic Errors
Run time error:
 Errors which lead at runtime by the run time translators are known as runtime errors.
 These are usually logical errors of programs. Ex: resource not found error, database table
not found error, network link failed error, etc..
 Using exception handling mechanism of java we can handle these errors.
What is Exception?
Exception is an unexpected run time error, leads to terminate the program without executing the
rest of statements.
What is Bug, Exception?
A program which terminates without executing the rest of statements, called a program with an
Exception.
A program which executes successfully with wrong output is called Bug in the program.
Types of Java Exception:
JVM classifieds the run time exceptions into 2 types.
1. Checked exception
2. Unchecked exception
1) Checked Exceptions:
Checked are the exceptions that are checked at compile time. If some code within a method throws
a checked exception, then the method must either handle the exception or it must specify the
exception using throws keyword.
For example, consider the following Java program that opens file at location “C:\test\a.txt” and
prints first three lines of it. The program doesn’t compile, because the function main() uses
FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses
readLine() and close() methods, and these methods also throw checked exception IOException

import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");

Page 1 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Output:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported
exception java.io.FileNotFoundException; must be caught or declared to be thrown
at Main.main(Main.java:5)

To fix the above program, we either need to specify list of exceptions using throws, or we need to
use try-catch block. We have used throws in the below program. Since FileNotFoundException is a
subclass of IOException, we can just specify IOException in the throws list and make the above
program compiler-error-free.

import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Output: First three lines of file “C:\test\a.txt”

2) Unchecked Exceptions:
Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to
the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything
else under throwable is checked.
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run.
The compiler allows it to compile, because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5)

Page 2 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Java Result: 1

Exception Hierarchy:
Throwable

Error Exception

IOException ClassNotFoundException RunTimeException CloneNotSupportedException

EOFException ArithmaticException
NumberFormatExceptio
n
FileNotFoundException ClassCastException

MalFormedURLException IllegalArgumentException

ArrayIndexOutOfBoun
UnknownHostException IlligalstateException dsException

NoSuchElementException

IndexOutofBoundsException

NullPointerException

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.

Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.

Page 3 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

ClassCastException Invalid cast.


IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

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

Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the Cloneable
CloneNotSupportedException
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 does not exist.

Keywords to work with Exceptions:


Java consists 5 keywords to work with exceptions and are defined in two groups
1. Exception Handler Keywords
2. Exception Throwable keywords
1) Exception Handler Keywords:
 Exception Handler keywords are used to handle the exceptions which are thrown by other
programs or statements.
 The exception handler keywords are try, catch, finally.
General Syntax of Handler Keywords:
try
{
//Exception Statements
//Exception Dependent Statements
}
catch(ExceptionType e)
{
//handler or alternate statements
}
:
:
:
catch(ExceptionType e)

Page 4 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

{
//handler or alternate statements
}
finally
{
//resource free statements for try block
}

Try block:
A block with name “try” without parameters known as try block.
Try block consists exception statements and its dependent statements.
In a program any no.of exception statements, any where we can define where ever an exception
occur in the program.
Try block in a program monitor the exception propagates the monitored exception to followed catch
block in sequential manner. So the try block is also known as Exception monitoring block.

Catch block:
 The block with name catch with a parameter, type of Exception known as catch block.
 Catch block in a program used to handle the propagated exceptions by the try block to
provide alternative statements.
 The catch block is also called as exception handler block.
 Every catch block should followed by try block. And a try block followed by any no. of catch
blocks.

Ex: Write a java program to demonstrate try and catch blocks?

import java.io.*;
import java.util.Scanner;
class ExonSimpleTry
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter two integers");
int a=0,b=0;
float res=0;
a=input.nextInt();
b=input.nextInt();
try
{
res=(float)(a)/(float)(b);
System.out.println("division="+res);
}
catch(ArithmeticException e)
{
System.out.println("second argument must not equal to zero");
}
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}

Page 5 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Multiple Catch Blocks:


 Sometimes there may be situation in which different exceptions may get raised by a single
try block statements and depending upon the type of exception thrown it must be caught.
 To handle such situation multiple catch blocks may exist for the single try block statements.
Syntax:
try{
//exception statements
}
catch(exception_type e)
{
//exception handling statements
}
catch(exception_type e)
{
//exception handling statements
}
:
:
catch(exception_type e)
{
//exception handling statements
}

Ex: Write a java program to demonstrate multiple catch blocks for single try?

import java.io.*;
class ExonMultiCatch
{
public static void main(String[] args)
{
int a=0,b=0;
float res=0;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=(float)(a)/(float)(b);
System.out.println("division="+res);
}
catch(ArithmeticException e)
{
System.out.println("second argument must not equal to zero");
}
catch(NumberFormatException e)
{
System.out.println("Arguments should be in int type only");
}
catch(IndexOutOfBoundsException e)
{
System.out.println("should enter 2 arguments only");

Page 6 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

}
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
Output:

Catch all Block:


 Catch all is a generalized handler block to handle unknown exception.
 Catch all should be define after completion of specific handler blocks, it should not be first. If
so compiler will raise compilation error.
 The real time application need one catch block after compilation of specific handler blocks.
Syntax:
try{
//exception statements
}
Catch(Exception_type e)
{
//exception handling statements
}
Catch(Exception_type e)
{
//exception handling statements
}
:
:
Catch(Exception_type e)
{
//exception handling statements
}
Catch(Exception e)
{
//Generalized exception
}

Nested Try Catch Blocks:


 A try block with in another try block is known as nested try block.
 This is used to execute the exception statements in the try block which are independent on
other exception statements in the same try block.
Syntax:
try{

Page 7 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

//exception statements
try{
//exception statements
}
Catch(Exception_type e)
{
//exception handling statements
}
:
:
Catch(Exception_type e)
{
//exception handling statements
}
::::::::::::::::::::::::;
}
Catch(Exception_type e)
{
//exception handling statements
}
:
:
Catch(Exception_type e)
{
//exception handling statements
}

Ex: write a java program to demonstrate nested try?


class ExonNestedtry
{
public static void main(String[] args)
{
try{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
float ans=0;
try{
ans=(float)a/(float)b;
System.out.println("result of a/b="+ans);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero exception");
}
}
catch(NumberFormatException e)
{
System.out.println("incorrect input data");
}
}
}

Page 8 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Output:

Finally Block:
 Finally is also known as mandatory block for both exception and without exception case.
 Finally block can define after try block and after the catch block also, but catch block should
follow by try block only.
 With exception case jvm executes try block & statements. Catch block statements and finally
block statements.
 Without exception case the jvm executes try block statements & direct finally block
statements.
 Finally block only ensures the resource declaration statements of try block, this is especially
used memory de allocations, file closing, network disconnections, database disconnections,
….etc. for the try block.
 The finally block provides the assurance of execution of some important code that must be
executed after the try block.
 Even though there is any exception in try block the statements assured by finally block are
sure to execute. These statements are sometimes called as clean up code.
Syntax:
Case-1:
try
{
//exception statements
//exception dependent statements
}
finally
{
//resource free for try block deals

}
Case-2:
Syntax:
try{
//exception statements
}
Catch(Exception_type e)
{
//exception handling statements
}
Catch(Exception_type e)
{
//exception handling statements

Page 9 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

}
:
:
Catch(Exception_type e)
{
//exception handling statements
}
finally
{
//resource free for try block deals

Ex: write a java program to demonstrate on finally block?


import java.util.Scanner;
class ExonFinally
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter two integers");
int a=0,b=0;
float res=-1;
a=input.nextInt();
b=input.nextInt();
try{
res=(float)(a)/(float)(b);
System.out.println("division="+res);
}
catch(ArithmeticException e)
{
System.out.println("divide by zero exception");
}
finally
{
System.out.println("This is from Finally block "+res);
}
}
}

Exception throwable keywords:


throw and throws are the exception throwable keywords used to throw an exception to
the caller, we need to throw an exception to the caller if the caller have dependant statements on
callable statements.
Differences between throw and throws:

Throw Throws
1. Throw is used to throw an exception 1. It is used to re-throw an exception to the
internally to the caller. caller.
2. Throws an exception object 2. Intimates what the exception type is re-

Page 10 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

throwing to the caller


3. Should be inside the method body 3. Should be along with the method
signature.
4. Throw only one exception object 4. It can specify any no.of exception class
types to re-throw to caller.
5. Usage of throw keyword to throw an 5. Usage of throws to re-throw an
exception intentionally to caller. exception to caller.
b(int x) b(int x) throws Exception1, Exception2,
{ …..,Exception_n
::::::::::::::: {
//throw new InsufficientException(); //got Exception_1
} :::::::::::
//get Exception_2
}

Ex: write a java program to demonstrate throw and throws

class InsufficientFundsException extends RuntimeException


{
public String toString()
{
return "Sorry insufficient fnds unable to create new acount";
}
}
class BankApplication
{
void createNewAccount(int amt,String acctype)
{
if(acctype.equals("SavingAcc"))
{
if(amt<1000)
throw new InsufficientFundsException();
else
System.out.println("Savings account created");
}
if(acctype.equals("CurrentAcc"))
{
if(amt<5000)
throw new InsufficientFundsException();
else
System.out.println("Current Account Created");
}
}
}
class ExonThrowThrows
{
public static void main(String args[])
{
BankApplication ba=new BankApplication();
try{

Page 11 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

ba.createNewAccount(6000,"CurrentAcc");
ba.createNewAccount(2000,"SavingAcc");
ba.createNewAccount(4000,"CurrentAcc");
}
catch(InsufficientFundsException e)
{
System.out.println(e);
}
System.out.println("After catch block");
}
}

Output:

Creating Own Exception Subclass:


 We can throw our own exceptions using the keyword throw.
 The syntax for throwing out own exception is
throw new Throwable’s subclass

Ex: write a java program to demonstrate throw and throws

class InsufficientFundsException extends RuntimeException


{
public String toString()
{
return "Sorry insufficient fnds unable to create new acount";
}
}
class BankApplication
{
void createNewAccount(int amt,String acctype)
{
if(acctype.equals("SavingAcc"))
{
if(amt<1000)
throw new InsufficientFundsException();
else
System.out.println("Savings account created");
}
if(acctype.equals("CurrentAcc"))
{
if(amt<5000)
throw new InsufficientFundsException();
else
System.out.println("Current Account Created");

Page 12 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

}
}
}
class ExonOwnException
{
public static void main(String args[])
{
BankApplication ba=new BankApplication();
try{
ba.createNewAccount(6000,"CurrentAcc");
ba.createNewAccount(2000,"SavingAcc");
ba.createNewAccount(4000,"CurrentAcc");
}
catch(InsufficientFundsException e)
{
System.out.println(e);
}
System.out.println("After catch block");
}
}

Output:

Page 13 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Threads:
Introduction:
 One of the exciting feature of windows operating system is that-it allows the user to handle
multiple tasks together. This facility in windows operating system is called multitasking.
 In java we can write the programs that perform multitasking using the multithreading
concept. Thus java allows to have multiple control flows in a single program by means of
multithreading.
 Definition: Thread is a tiny program running continuously. It is sometimes called as light-
weight-process. But there lies differences between thread and process.
Difference between thread and process:
Thread Process
1. Thread is a light weight process 1. Process is heavy weight process
2. Threads do not require separate address 2. Each process requires separate address
space for its execution. It runs in the space to execute.
address space of the process to which it
belongs to

Difference between Multithreading and Multitasking:


Multithreading Multitasking
1. Thread is a fundamental unit of 1. Program or process is a fundamental
multithreading unit of multitasking environment
2. Multiple parts of a single program get 2. Multiple programs get executed in
executed in multithreading environment. multitasking environment
3. During multithreading the processor 3. During multitasking the processor
switches between multiple threads of switches between multiple programs or
the program. processes.
4. It is cost effective because CPU can be 4. It is expensive because when a particular
shared among multiple threads at a process uses CPU other processes has to
time. wait.
5. It is highly efficient. 5. It is less efficient in comparison with
multithreading.
6. It helps in developing efficient 6. It helps in developing efficient operating
application programs. system programs.

 Thread always exists in any one of the following states.


o New or create state
o Runnable state
o Waiting state
o Timed waiting state
o Blocked state
o Terminated state

Thread Life Cycle:


Thread life cycle specifies how a thread gets processed in the java program by executing various
methods. Following figure represents how a particular thread can be in one of the state at any time.

Page 14 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

New
Thread
starts Exit
Completion
Runnable Terminated
Waiting Waiting
Interval IO
for IO
ends completed
interval Request
Waiting Timed waiting Blocked

Fig: Life cycle of thread


New state:
When thread starts its life cycle it enters in the new state or a create state.
Runnable State:
This is a state in which a thread starts executing.
Waiting state:
Sometimes one thread has to undergo in waiting state because another thread starts executing.
Timed waiting state:
There is a provision to keep a particular threading waiting for some time interval. This
allows to execute high prioritized threads first. After the timing gets over, the thread in waiting state
enters in Runnable state.
Blocked State:
When a particular thread issues an input/output request then operating system sends it in
blocked state until the I/O operation gets completed. After the I/O completion the thread is sent
back to the Runnable state.
Terminated State:
After successful completion of the execution the thread in Runnable state enters the terminated
state.
Creating Threads:
 Threads can be in various states such as new, Runnable, waiting, blocked and so on. After
successful completion of a thread, it gets terminated.
 In java we can implement the thread programs using two approaches-
o Using Thread class
o Using Runnable interface
 Below figure shows the thread implementation model.

Page 15 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Implementation of Thread
extends implements

Thread Runnable
(class) (interface)

run()
method

Fig:2 creation of java threads


 As given in figure:2 there are two methods by which we can write the java thread programs.
i.e. one by extending Thread class, and by implementing the Runnable interface.
 The run() method is the most important method in any threading program. By using this
method the thread’s behavior can be implemented. The run() method can be written as
follows.
public void run()
{
//statements for implementing thread
}
 For invoking the thread’s run method the object of a thread is required. This object can be
obtained by creating and initiating a thread using the start() method.

class MyRunnable extends A implements Runnable class MyThread extends Thread


{ {
public void run() Public void run()
{ {
//concurrent statements //concurrent statements
} }
} }
Thread API:
Constructors:
1. Thread(): create a new thread object
2. Thread(Runnable target): creates a new thread object with the given Runnable object as
target to invoke Runnable object’s run() method.
3. Thread(String name): create a new thread object with the given thread name.
4. Thread(ThreadGroup group, String name): creates a new thread object with the given name
and places in a given thread group name.
Methods:
1. static Thread currentThread(): returns a reference to the currently executing thread object.
2. String getName(): returns the threads name.
3. int getPriority(): returns thread’s priority.
4. Thread.State getState(): returns the state of the thread.
5. ThreadGroup getThreadGroup(): returns the Thread Group to which this thread belongs to.
6. void interrupt(): interrupts the current method.
7. boolean isAlive(): tests if the current thread is alive.
8. boolean isDaemon(): tests if the current thread is daemon thread.
9. void join(): wait for current thread to die.

Page 16 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

10. void setDaemon(Boolean on): marks the current thread as either a daemon thread.
11. void setName(String name): used to set the name for thread.
12. void setPriority(int newPriority): used to set the priority.
13. public static void sleep(long milliseconds) throws InterruptedException: temporarily blocks
the current thread execution for the specified no.of milliseconds.
14. void start(): starts the current thread execution.
15. static void yield(): pause the current thread and allows other threads to execute.

Steps to define Threads in JAVA program:


Case-1: Define Threads using Runnable Object.
1. Define a class and implements Runnable Interface.
class MyRunnable implements Runnable
{
public void run()
{
//processes
}
}
2. Define Thread Object with Runnable object as target.
Thread t=new Thread(new MyRunnable());
3. Start the Thread
t.start();
Case-2: Defining Threads using Thread Class Object:
1. Define a class and extends to Thread Class.
class MyThread extends Thread
{
public void run()
{
//processes
}
}
2. Define Thread Object.
MyThread mt=new MyThread();
3. Start the Thread
mt.start();

Ex: Write a java program to demonstrate Threads concept.


class Task1 extends Thread
{
void print1to100()
{
for(int i=1;i<=100;i++)
System.out.println("Task1 prints: "+i);
}
public void run()
{
print1to100();
}
}

Page 17 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

class Task2 implements Runnable


{
void print100to1()
{
for(int i=100;i>=1;i--)
System.out.println("Task2 prints: "+i);
}
public void run()
{
print100to1();
}
}
class ExonThreads
{
public static void main(String ar[])
{
Task1 t1=new Task1(); //this is thread object
Thread t2=new Thread(new Task2()); //this is with Runnable object as target
t1.start();
t2.start();
}
}
Output:

Ex: Write a java program to get the main thread default properties, update those properties with
new values.
class ExonMainThreadProperties
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
System.out.println("Main Thread name: "+t.getName());
System.out.println("Main Thread Priority: "+t.getPriority());

Page 18 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

System.out.println("Main Thread group name:


"+t.getThreadGroup().getName());
t.setName("Vamshi thread");
t.setPriority(10);
System.out.println("Updated values are");
System.out.println("Main Thread name: "+t.getName());
System.out.println("Main Thread Priority: "+t.getPriority());
}
}
Output:

Thread Priority:
 In a multi threading program we can start the thread based on the preferences of a given
task by setting priority to the threads.
 Every thread has the default priority given by JVM before start the execution is ‘5’.
 In java we can set the thread priorities between 1 to 10. Other than this range is found by
JVM then it raise the IllegalArgumentException.
Note:
 Thread without priority or equal priority their execution is depends upon OS process
management technique. i.e. we can’t expect which thread will start first.
 The Thread which has highest priority that thread execution will starts first.

Ex: write a java program to demonstrate thread priority.


class Task1 extends Thread
{
void print1to100()
{
for(int i=1;i<=100;i++)
System.out.println("Task1 prints: "+i);
}
public void run()
{
print1to100();
}
}

class Task2 implements Runnable


{
void print300to400()
{

Page 19 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

for(int i=300;i<=400;i++)
System.out.println("Task2 prints: "+i);
}
public void run()
{
print300to400();
}
}
class ExonThreadPriority
{
public static void main(String ar[])
{
Task1 t1=new Task1();
Thread t2=new Thread(new Task2());
t2.setPriority(10);
t1.setPriority(3);
t1.start();
t2.start(); //here t2 thread starts first
}
}

Output:

Sleep, Yield, Stop methods:


 wait(), sleep(time) are the methods forces the current thread to bring into blocked state.
The wait state thread needs notifications to get back into Runnable state using notify() or
notifyAll() methods.
 Timed waiting state threads will automatically get back into Runnable state after completion
of the given blocked time.
 Yield() method forces the current thread to bring into Runnable state. i.e. it temporarily
pauses the current thread execution.
 Stop() method forces the current thread to move into the terminated state. These threads
will not get back into the Runnable state.
Ex: write a java program to demonstrate the wait,yield, stop methods.
class SleepThread extends Thread

Page 20 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Sleep thread" +i);
if(i==3)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}
};
class StopThread extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Stop thread" +i);
if(i==3)
{
stop();
}
}
}
};
class YieldThread extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Yield thread" +i);
if(i==3)
{
Thread.yield();
}
}
}
}
class ExonSleepStopYield
{
public static void main(String arg[])
{

Page 21 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

SleepThread slp=new SleepThread();


StopThread stp=new StopThread();
YieldThread yt=new YieldThread();
slp.start();
stp.start();
yt.start();
}
}

Output:

isAlive() and Join() Methods:


 isAlive() method returns the status of availability of a thread.
 A thread is available only in active thread state.
 Join() method is useful in co-coordinating threads. This method makes the current thread to
wait until other specified thread terminates.

Ex: Write a java program to demonstrate the isAlive() and join() methods.
class ThreadB extends Thread
{
public void run()
{
for(int i=100;i<=105;i++)
{
System.out.println("thread B printss "+i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}

Page 22 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

};
class ThreadA extends Thread
{
ThreadB tb;
ThreadA()
{
tb=new ThreadB();
System.out.println("ThreadB status "+tb.isAlive());
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("ThreadA "+i);
if(i==5)
{
tb.start();
System.out.println("ThreadB status "+tb.isAlive());
try
{
tb.join();
}
catch(Exception e)
{
}
System.out.println("ThreadB status "+tb.isAlive());
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}
class ExonIsaliveJoin
{
public static void main(String ar[])
{
ThreadA ta=new ThreadA();
ta.start();
}
}

Output:

Page 23 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Thread States:
 getState() method returns Thread.Status.

Ex: write a java program to demonstrate the getState() method.

class MyThread extends Thread


{
public void run()
{
System.out.println(super.getState().name()); //runnable state
}
};
class ExonThreadState
{
public static void main(String[] args)
{
MyThread mt = new MyThread();
System.out.println(mt.getState().name()); //new state
mt.start();
try
{
mt.join();
}
catch(Exception e)
{
}
System.out.println(mt.getState().name()); //terminate state
}
}

Output:

Page 24 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Thread Groups:
Main group

Main thread

My group 1

User thread 1
User thread 2

My group 2

User thread 3
User thread 4

 Thread groups are useful to group the list of threads to which have a common functionality.
 Using thread groups we can get the control on group of threads at a time.
 The default thread group for all user threads is main group, which is defined by the JVM
while executing java program.
 Super thread group for all user defined thread group is also main group, every thread group
hava default priority is 10.
 We can define thread group object by invoking the following constructors
Syn:
ThreadGroup tg1=new ThreadGroup(“mygroup1”);

ThreadGroup tg2=new ThreadGroup(tg1, “mygroup2”);

Constructors:
1. ThreadGroup(String name): constructs a new thread with specified name.
2. ThreadGroup(ThreadGroup parent, String name): which is used to define sub group within
the main group.
Methods:
1. int activeCount(): returns the count of active threads in a thread group.
2. int activeGroupCount(): retrns no.of active groups in a thread group.
3. void destroy(): destroy current thread group and all of sub groups.
4. String getName(): returns name of the thread group.
5. void list(): prints the information about current thread group to the standard output.

Ex: write a java program to group the user threads under user thread groups and display
properties of thread group.

Page 25 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

class MyThread extends Thread


{
MyThread(ThreadGroup tg, String name)
{
super(tg,name);
}
public void run()
{
try
{
Thread.sleep(5000);
}
catch(Exception e)
{
}
}
}
class ExonThreadGroup
{
public static void main(String[] args) throws Exception
{
Thread mt=Thread.currentThread();
ThreadGroup mtg=mt.getThreadGroup();
System.out.println("main thread group"+mtg.getName());
ThreadGroup mtg1=new ThreadGroup("MyGroup1");
MyThread mt1=new MyThread(mtg1,"Thread1");
MyThread mt2=new MyThread(mtg1,"Thread2");
MyThread mt3=new MyThread(mtg1,"Thread3");
mt1.start();
mt2.start();
mt3.start();
ThreadGroup mtg2=new ThreadGroup(mtg1,"mygroup2");
MyThread mt4=new MyThread(mtg2,"Thread4");
MyThread mt5=new MyThread(mtg2,"Thread5");
mt4.start();
mt5.start();
System.out.println("Thread group under main thread
group"+mtg.activeGroupCount());
System.out.println("Active threadd count under main thread
group"+mtg.activeCount());
System.out.println("main thread group details");
mtg.list();
System.out.println("my thread group1 details");
mtg1.list();

}
}

Output:

Page 26 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Synchronizing Threads:
 When 2 or more threads need to access shared memory, then there is some way to ensure
that the access to the resource will be only one thread at a time.
 The process of ensuring one access at a time by one thread is called synchronization.
 The synchronization is the concept which is based on monitor.
 Monitor is used a mutually exclusive lock or mutex.
 When a thread owns this monitor then the other threads cannot access the resources. Other
threads have to be in waiting state.
 In java every object has implicit monitor associated with it. For entering in object’s monitor,
the method is associated with keyword synchronized. When a particular method is in
synchronized state then other threads have to be in waiting state.
 There are 2 ways to achieve this synchronization.
o Using synchronized methods
o Using synchronized blocks (set of statements)
Note:
 Only methods can be synchronized but the variables and classes cannot be synchronized.
 Each object has one lock.
 A class contains several methods and all methods need not be synchronized.
 If two threads in a class want to execute synchronized methods and both the methods are
using the same instance of a class then only one thread can access the synchronized method
at a time.
 We cannot synchronize the constructors.
 A thread can acquire more than one lock.
Case 1: defining synchronized methods:
synchronized void makeReservation(int seats)
{
// process which need to be lock by a thread
}
Case 2: defining synchronized block:
synchronized(this)
{
// super class inherited data which need to be lock by a thread
}

Page 27 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Ex: write a java program to demonstrate railway ticket booking using synchronization or mutual
exclusion

class Reservation
{
int avlseats=5;
synchronized void makeReservation(int seats)
{
Thread t=Thread.currentThread();
if(seats<=avlseats)
{
System.out.println(t.getName()+" Seats are available. wait reservation
in progress....");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
avlseats=avlseats-seats;
System.out.println(t.getName()+" Take your Ticket.. Happy Journey");
}
else
{
System.out.println(t.getName()+" Sorry seats are not available");
}
}
}
class MyThread extends Thread
{
Reservation r;
int seats;
MyThread(Reservation r, int seats)
{
this.r=r;
this.seats=seats;
}
public void run()
{
r.makeReservation(seats);
}
}
class ExonThreadSync
{
public static void main(String ar[])
{
Reservation r=new Reservation();
MyThread mt1=new MyThread(r,2);
MyThread mt2=new MyThread(r,4);
MyThread mt3=new MyThread(r,3);

Page 28 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

mt1.start();
mt2.start();
mt3.start();
}
}

Output:

 The above output is without synchronization.


 But the below output is with synchronization.

Inter-Thread Communication:
 Two or more threads can communicate with each other by exchanging the messages. This
mechanism is called the inter thread communication. There are 3 methods that take part in
inter thread communication and those are-
notify() If a particular thread is in the sleep mode then that thread can be resumed using
the nitify call.
notifyall() This method resumes all the threads that are in suspended state
wait() The calling thread can be send into sleep mode.

Ex: write a java program to demonstrate the thread communication methods (Producer Consumer
Problem)?
class Myclass
{
int n;
boolean flag=false;
synchronized int get()
{
if(!flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception");
}
}
System.out.println("consumer Consuming"+n);

Page 29 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

flag=false;
notify();
return n;
}
synchronized void put(int n)
{
if(flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception");
}
}
this.n=n;
flag=true;
System.out.println("Producer producing "+n);
notify();

}
}
class Producer implements Runnable
{
Myclass obj;
Producer(Myclass obj)
{
this.obj=obj;
new Thread(this,"Producer").start();
}
public void run()
{
for(int i=0;i<10;i++)
{
obj.put(i);
}
}
}
class Consumer implements Runnable
{
Myclass obj;
Consumer(Myclass obj)
{
this.obj=obj;
new Thread(this,"Consumer").start();
}
public void run()
{
for(int i=0;i<10;i++)

Page 30 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

{
obj.get();
}
}
}

class InterThread
{
public static void main(String[] args)
{
Myclass tobj=new Myclass();
new Producer(tobj);
new Consumer(tobj);
}
}
Output:

Thread Properties:
Various thread properties are
1. Thread Priorities
2. Daemon Thread
3. Thread Group

1. Daemon Thread:
 The threads which are executing in the background are called Daemon Threads.
 The main objective of daemon thread is to provide support for non-daemon threads. The
daemon threads are also known as service provider threads.
 Ex: in image processing applications, using a thread we can keep on present the highly
resolution images on screen, at the same time we need to refresh the screen
automatically. So we need a daemon thread.
 If the parent thread is daemon, then the child is also by default daemon, and if the parent is
non-daemon then the child is also by default non-daemon.
 Once the last non-daemon thread terminates all the daemon threads will be terminated
automatically.

Syn:

Page 31 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

MyThread mt=new MyThread();


Mt.setDaemon(true);
Mt.start();
To know the status of daemon thread:
Boolean b=mt.isDaemon();

Ex: write a java program to demonstrate daemon threads?

class MyThread extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Providing service "+i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
System.out.println("end of daemon thread");
}
};
class ExonDaemonThread
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
System.out.println("deamon thread before creating: "+mt.isDaemon());
mt.setDaemon(true);
System.out.println("deamon thread after creating: "+mt.isDaemon());
mt.start();
for(int i=100;i<=105;i++)
{
System.out.println("Main thread prints "+i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
System.out.println("End of the main thread");
}
}

Page 32 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Output:
1. The below output is without daemon thread.

2. The below output is with the daemon thread

Enum Types
An enum type is a special data type that enables for a variable to be a set of predefined constants.
The variable must be equal to one of the values that have been predefined for it. Common examples
include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Because they are constants, the names of an enum type's fields are in uppercase letters.
In the Java programming language, you define an enum type by using the enum keyword. For
example, you would specify a days-of-the-week enum type as:
You should use enum types any time you need to represent a fixed set of constants. That includes
natural enum types such as the planets in our solar system and data sets where you know all
possible values at compile time—for example, the choices on a menu, command line flags, and so
on.
Here is some code that shows you how to use the Day enum defined above:

Page 33 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

public class EnumTest {


Day day;

public EnumTest(Day day) {


this.day = day;
}

public void tellItLikeItIs() {


switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;

case FRIDAY:
System.out.println("Fridays are better.");
break;

case SATURDAY: case SUNDAY:


System.out.println("Weekends are best.");
break;

default:
System.out.println("Midweek days are so-so.");
break;
}
}

public static void main(String[] args) {


EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
The output is:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Page 34 of 35
Sub: Java Programming
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY & SCIENCES
RamaKrishna Colony, Karimangar
SubCode: A40503
Unit: III
Department of CSE
Year/Sem: II B.tech I Sem (R13)

Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance,
an enum cannot extend anything else.

In the following example, Planet is an enum type that represents the planets in the solar system.
They are defined with constant mass and radius properties.
Each enum constant is declared with values for the mass and radius parameters. These values are
passed to the constructor when the constant is created. Java requires that the constants be defined
first, prior to any fields or methods. Also, when there are fields and methods, the list of enum
constants must end with a semicolon.

Note: The constructor for an enum type must be package-private or private access. It automatically
creates the constants that are defined at the beginning of the enum body. You cannot invoke an
enum constructor yourself.

Page 35 of 35

You might also like