Ii Ii JP Unit-3
Ii Ii JP Unit-3
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)
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);
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
EOFException ArithmaticException
NumberFormatExceptio
n
FileNotFoundException ClassCastException
MalFormedURLException IllegalArgumentException
ArrayIndexOutOfBoun
UnknownHostException IlligalstateException dsException
NoSuchElementException
IndexOutofBoundsException
NullPointerException
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)
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.
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.
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)
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:
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
}
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
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)
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:
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
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
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
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.
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)
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)
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.
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:
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)
Output:
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.
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”);
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)
}
}
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:
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)
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.
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)
case FRIDAY:
System.out.println("Fridays are better.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
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