0% found this document useful (0 votes)
2 views

OOP thr Java-UNIT 3

This document covers exception handling and multithreading concepts in Java, detailing the mechanisms for managing exceptions, including the use of keywords like try, catch, throw, throws, and finally. It explains the types of exceptions (checked and unchecked), their hierarchy, and provides examples of handling exceptions through various coding scenarios. Additionally, the document discusses multithreading concepts, thread life cycles, and synchronization techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

OOP thr Java-UNIT 3

This document covers exception handling and multithreading concepts in Java, detailing the mechanisms for managing exceptions, including the use of keywords like try, catch, throw, throws, and finally. It explains the types of exceptions (checked and unchecked), their hierarchy, and provides examples of handling exceptions through various coding scenarios. Additionally, the document discusses multithreading concepts, thread life cycles, and synchronization techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

OOP through Java UNIT-3

UNIT-III

Exception handling and Multithreading-- Concepts of exception handling, benefits of


exception handling, Termination or presumptive models, exception hierarchy, usage of try,
catch, throw, throws and finally, built in exceptions, creating own exception subclasses.
String handling, Exploring java.util. Differences between multithreading and multitasking,
thread life cycle, creating threads, thread priorities, synchronizing threads, inter thread
communication, thread groups, daemon threads. Enumerations, autoboxing, annotations,
generics.

Concepts of exception handling


An exception in java programming is an abnormal situation that is araised 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 exceptions automatically.

There are many cases where abnormal conditions happen during program execution, suchas
 When we try to open a file that does not exist may lead to an exception.
 When the user enters invalid input data, it may lead to an exception.
 When a network connection has lost during the program execution may lead to an
exception.
 When we try to access the memory beyond the allocated range may lead to an
exception.
 The physical device problems may also lead to an exception.

The exception object contains information about the exception including its type and the
state of the program when the error occurred.

In java, the exception handling mechanism uses five keywords such as try, catch, finally,
throw and throws.

Benefits of Exception Handling


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.

Termination or Presumptive models


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.


 Termination Model

P.Ramesh, Assistant Professor, AIML Dept, 1


TKREC
OOP through Java UNIT-3
 Presumptive Model

Termination Model
In the termination model, when a method encounters an exception, further processing in
that method is terminated and control is transferred to the nearest catch block that can
handle the type of exception encountered.

In other words we can say that in termination model the error is so critical there is no way to
get back to where the exception occurred.

Presumptive Model
The alternative of termination model is presumptive model. In presumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In presumptive model we hope to continue the execution after the
exception is handled.

In presumptive model we may use a method call that want resumption like behaviour. We
may also place the try block in a while loop that keeps re-entering the try block until the
result is satisfactory.

Exception Hierarchy

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

A hierarchy of Java Exception classes are given below:

P.Ramesh, Assistant Professor, AIML Dept, 2


TKREC
OOP through Java UNIT-3

P.Ramesh, Assistant Professor, AIML Dept, 3


TKREC
OOP through Java UNIT-3

General form of Exception Handling


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
Finally
{
// block of code to be executed before try block ends
}

Try Block

No Exception

Throws exception object

arise or

No Catch Block
Exceptional Handler
appropriate

Catch

block

Finally Block
Optional part

// Simple Exception Example without try-catch block

class Exception
{
public static void main(String args[])
{
int d = 0;

P.Ramesh, Assistant Professor, AIML Dept, 4


TKREC
OOP through Java UNIT-3
int a = 42 / d;
}
}
OUTPUT
D:\TKREC\Java>java Exception
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exception.main(Exception.java:9)

Types of Java Exception


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:


 Checked Exception
 Unchecked Exception
 Error

Checked Exception
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 following are a few built-in classes used to handle checked exceptions in java.
 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
 UnknownHostException

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.

Example
import java.io.*;

public class CheckedExceptions


{
public static void main(String[] args)
{
File f = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");
try
{
FileReader obj = new FileReader(f);
}

P.Ramesh, Assistant Professor, AIML Dept, 5


TKREC
OOP through Java UNIT-3
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
D:\TKREC\Java>java CheckedExceptions
java.io.FileNotFoundException: C:\Users\User\Desktop\Today\Sample.txt (The
system cannot find the path specified)

Unchecked Exception
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 of compilation.

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 the
RuntimeException class which is a child class of Exception class. The unchecked exception is
also known as a run-time exception

Example
public class UncheckedException
{
public static void main(String[] args)
{
int list[] = {10, 20, 30, 40, 50};
System.out.println(list[6]); //ArrayIndexOutOfBoundsException

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

String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
OUTPUT
D:\TKREC\Java>java UncheckedException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out
of bounds for length 5 at UncheckedException.main(UncheckedException.java:4)

P.Ramesh, Assistant Professor, AIML Dept, 6


TKREC
OOP through Java UNIT-3
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Usage of try, catch, throw, throws and finally

Keyword Description
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" keyword is used to declare exceptions. It doesn't throw
an exception. It specifies that there may occur an exception in the
method. It is always used with method signature

Using Try and Catch Blocks


In java, the try and catch, both are the keywords used for exception handling. The keyword
try is used to define a block of code that will be tests the occurrence of an exception.

The keyword catch is used to define a block of code that handles the exception occurred in
the respective try block. Both try and catch are used as a pair. Every try block must have one
or more catch blocks. We cannot use try without at least one catch, and catch alone can be
used (catch without try is not allowed).

The following is the syntax of try and catch blocks.


try
{
…..
code to be tested

}
catch(ExceptionType object)
{

Code for handling the exception
}

Example
import java.util.Scanner;

public class TryCatchExample


{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);

P.Ramesh, Assistant Professor, AIML Dept, 7


TKREC
OOP through Java UNIT-3
System.out.println("Enter the a and b values: ");
try
{
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: Value of divisor cannot be ZERO");
}
}
}

OUTPUT:
D:\TKREC\Java>java TryCatchExample
Enter the a and b values:
5
0
Problem info: Value of divisor cannot be ZERO

// Simple try catch example

public class TryCatchExample


{
public static void main(String[] args)
{
try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
catch(Exception e)
{
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

P.Ramesh, Assistant Professor, AIML Dept, 8


TKREC
OOP through Java UNIT-3
OUTPUT:
D:\TKREC\Java>java TryCatchExample
Problem info: ArrayIndexOutOfBoundsException has occured.

// another try catch example

class TryCatch
{
public static void main(String args[])
{
int[] no={1,2,3};
try
{
System.out.println(no[3]); //may throw exception
}
//handling the exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
System.out.println("Quit");
}
}

OUTPUT:
D:\TKREC\Java>javac TryCatch.java
D:\TKREC\Java>java TryCatch
Out of bounds
Quit

Multiple Catch Clauses


In java programming language, a try block may have one or more number of catch blocks.
That means a single try statement can have multiple catch clauses. When a try block has
more than one catch block, each catch block must contain a different exception type to be
handled.

The multiple catch clauses are defined when the try block contains the code that may lead to
different type of exceptions. The try block generates only one exception at a time, and at a
time only one catch block is executed.

When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general. The catch block with Exception class handler
must be defined at the last.

// Multiple Catch Blocks Example

public class MultipleCatchExample


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

P.Ramesh, Assistant Professor, AIML Dept, 9


TKREC
OOP through Java UNIT-3
try
{
int array[] = {1,2};
array[4]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("Devide by Zero");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Array Index Out Of Bound");
}
catch(Exception e)
{
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
OUTPUT:
D:\TKREC\Java>java MultipleCatchExample
Devide by Zero

// Multiple catch Blocks Example2

public class MultipleCatch


{
public static void main(String[] args)
{
try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}

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


}
}
OUTPUT:
D:\TKREC\Java>java MultipleCatch
ArrayIndexOutOfBounds Exception occurs
rest of the code

P.Ramesh, Assistant Professor, AIML Dept, 10


TKREC
OOP through Java UNIT-3

Nested try statements


The java allows to write a try statement inside another try statement. A try block within
another try block is known as nested try block.
When there are nested try blocks, each try block must have one or more separate catch
blocks.

In case of nested try blocks, if an exception occured in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to
handle it.

// NestedTry Example
public class NestedTryExample
{
public static void main(String[] args)
{

try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try
{
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: Value of divisor cannot be ZERO.");
}
catch(Exception e)
{
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
OUTPUT:
D:\TKREC\Java>java NestedTryExample
Problem info: ArrayIndexOutOfBoundsException has occured.

Java throw Keyword


The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
P.Ramesh, Assistant Professor, AIML Dept, 11
TKREC
OOP through Java UNIT-3

The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
 Using throw keyword only object of Throwable class or its sub classes can be thrown.
 Using throw keyword only one exception can be thrown.
 The throw keyword must followed by an throwable instance.

The following is the general syntax for using throw keyword in a try block.
throw instance;

Here the instance must be throwable instance and it can be created dynamically using new
operator.

// Throw Example

class ThrowExample
{
public static void divideByZero()
{
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args)
{
divideByZero();
}
}
OUTPUT:
D:\TKREC\Java>java ThrowExample
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at ThrowExampke.divideByZero(ThrowExample.java:8)
at ThrowExample.main(ThrowExample.java:13)

In this example, we are explicitly throwing an ArithmeticException.


Note: ArithmeticException is an unchecked exception. It's usually not necessary to handle
unchecked exceptions.

// Simple Throw Example2

class ThrowExample2
{
void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("Welcome to vote");
}
public static void main(String[] args)
{
ThrowExample2 obj=new ThrowExample2();

P.Ramesh, Assistant Professor, AIML Dept, 12


TKREC
OOP through Java UNIT-3
obj.validate(13);
// obj.validate(19);
System.out.println("Rest of code");
}
}
OUTPUT:
D:\TKREC\Java>java ThrowExample2
Exception in thread "main" java.lang.ArithmeticException: not valid
at ThrowExample2.validate(ThrowExample2.java:6)
at ThrowExample2.main(ThrowExample2.java:13)

D:\TKREC\Java>java ThrowExample2
Welcome to vote
Rest of code

Java throws keyword


The throws keyword specifies the exceptions that a method can throw to the default handler
and does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration

Its syntax is:


accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 …
{
// code
}

// Throws Keyword Example

class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
OUTPUT:
D:\TKREC\Java>java ThrowsDemo
Inside throwOne.

P.Ramesh, Assistant Professor, AIML Dept, 13


TKREC
OOP through Java UNIT-3
Caught java.lang.IllegalAccessException: demo

// Throws Keyword Example2

class ThrowsExample
{
void validate(int age) throws ArithmeticException
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("Welcome to vote");
}
public static void main(String[] args)
{
try
{
ThrowsExample obj=new ThrowsExample();
obj.validate(13);
//obj.validate(19);
}
catch(ArithmeticException e)
{
System.out.println("e");
}
System.out.println("Rest of code");
}
}
OUTPUT:
D:\TKREC\Java>java ThrowsExample
e
Rest of code
D:\TKREC\Java>java ThrowsExample
Welcome to vote
Rest of code

// Java throws Keyword in Files

import java.io.*;
class ThrowsDemoFiles
{
public static void findFile() throws IOException
{
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args)
{
try

P.Ramesh, Assistant Professor, AIML Dept, 14


TKREC
OOP through Java UNIT-3
{
findFile();
}
catch(IOException e)
{
System.out.println(e);
}
}
}

When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.

If a method does not handle exceptions, the type of exceptions that may occur within it must
be specified in the throws clause so that methods further up in the call stack can handle them
or specify them using throws keyword themselves.

The findFile() method specifies that an IOException can be thrown. The main() method calls
this method and handles the exception if it is thrown.

OUTPUT:
D:\TKREC\Java>javac ThrowsDemoFiles.java
D:\TKREC\Java>java ThrowsDemoFiles
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

Java finally block


Java finally block is a block that is used to execute important code such as closing
connection, stream etc. Java finally block is always executed whether exception is handled or
not. Java finally block follows try or catch block.

Why use java finally


Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
 Only one finally block is allowed for each try block.
 Use of finally block is optional.

// Finally Block Example

class FinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
// int data=25/0
System.out.println(data);
}
catch(NullPointerException e)
{
P.Ramesh, Assistant Professor, AIML Dept, 15
TKREC
OOP through Java UNIT-3
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT:
D:\TKREC\Java>java FinallyBlock
5
finally block is always executed
rest of the code...

if we give int data=25/0 then will get this

D:\TKREC\Java>java FinallyBlock
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyBlock.main(FinallyBlock.java:9)

The throws keyword is used to declare which exceptions can be thrown from a method,
while the throw keyword is used to explicitly throw an exception within a method or block of
code. The throws keyword is used in a method signature and declares which exceptions can
be thrown from a method

Java Built – In Exceptions


Inside the standard package java.lang, Java defines several exception classes. A few have
been used by the preceding examples. 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

The unchecked exceptions defined in java.lang are listed in Table 10-1.

Table 10-2 lists those exceptions defined by java.lang that must be included in a method’s
throws list if that method can generate one of these exceptions and does not handle it itself.
These are called checked exceptions.

Java defines several other types of exceptions that relate to its various class libraries

P.Ramesh, Assistant Professor, AIML Dept, 16


TKREC
OOP through Java UNIT-3
List of Unchecked exceptions

List of Checked exceptions

P.Ramesh, Assistant Professor, AIML Dept, 17


TKREC
OOP through Java UNIT-3
Java User Defined Exception

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.

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. By the help of custom exception, you can have your own exception and message.

// User Defined Exception


package customExceptionProgram;

class MyException extends Exception


{
// Declare default constructor.
MyException()
{
}
}
public class UserException
{
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it using throw clause.
MyException obj = new MyException();
throw obj;
}
catch (MyException ex)
{
System.out.println("Caught a user defined exception");
}
}
}
OUTPUT
D:\TKREC\Java>java UserException
Error: Could not find or load main class UserException
Causedby: java.lang.NoClassDefFoundError: customExceptionProgram/UserException
(wrong name: UserException)

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.

// User Defined Exception2


import java.util.Scanner;

class NotEligibleException extends Exception


{

P.Ramesh, Assistant Professor, AIML Dept, 18


TKREC
OOP through Java UNIT-3
NotEligibleException(String msg)
{
super(msg);
}
}
class VoterList
{
int age;
VoterList(int age)
{
this.age = age;
}

void checkEligibility()
{
try
{
if(age < 18)
{
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrats! You are eligible for vote.");
}
catch(NotEligibleException nee)
{
System.out.println(nee.getMessage());
}
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList obj = new VoterList(age);
obj.checkEligibility();
}
}
OUTPUT:
D:\TKREC\Java>java VoterList
Enter your age in years:
25
Congrats! You are eligible for vote.
D:\TKREC\Java>java VoterList
Enter your age in years:
12
Error: Not eligible for vote due to under age.

P.Ramesh, Assistant Professor, AIML Dept, 19


TKREC
OOP through Java UNIT-3
String handling
String is an object that represents sequence of characters surrounded by double
quotations. In Java, String is represented by String class which is located into java.lang
package. In the background, the string values are organized as an array of a
character data type

It is probably the most commonly used class in java library. In java, every string that we
create is actually an object of type String. One important thing to notice about string object is
that string objects are immutable that means once a string object is created it cannot be
changed.

What is an Immutable object?


An object whose state cannot be changed after it is created is known as an Immutable object.
String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are
immutable.

The String class implements Serializable, Comparable, and CharSequence


interfaces.

Example
String siteName = "JavaProgram.com";
siteName = "JavaProgram.com";

String handling methods:


public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Tutorials";
String siteName = "JavaProgram.com";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java JavaStringExample
Length of title: 14
Char at index 3: a
Index of 'T': 5
Last index of 'a': 11
Empty: false
Ends with '.com': true
Equals: false

P.Ramesh, Assistant Professor, AIML Dept, 20


TKREC
OOP through Java UNIT-3
Sub-string: am.co
Upper case: JAVAPROGRAM.COM

Exploring java.util.

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

Advantages of Java Multithreading


 It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
 Improved performance and concurrency.

Differences between multithreading and multitasking


Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU.

Multitasking can be achieved in two ways:


 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

Process-based Multitasking (Multiprocessing):- Executing several tasks simultaneously,


where each task is a separate independent process. This process based multitasking is OS
level concept
Example: -Typing some text in Editor, Listening audio songs, Download a file from Net
 Each process has an address in memory. In other words, each process allocates a
separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.

Thread-based Multitasking (Multithreading):- Executing several independent parts (OR)


tasks simultaneously, where each task is a separate independent part of the same program.
This thread based multitasking is programmatic level concept
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Note: At least one process is required for each thread

P.Ramesh, Assistant Professor, AIML Dept, 21


TKREC
OOP through Java UNIT-3
What is Thread in java: - A thread is a lightweight sub process, 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

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.

Note: At a time one thread is executed only

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.

Commonly Used Methods of thread class:-


 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread. JVM calls the run() method on
the thread.
 public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
P.Ramesh, Assistant Professor, AIML Dept, 22
TKREC
OOP through Java UNIT-3
miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing
thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.
 public static boolean interrupted(): tests if the current thread has been interrupted

The life cycle of a thread in java is shown in the following figure.

(OR)

P.Ramesh, Assistant Professor, AIML Dept, 23


TKREC
OOP through Java UNIT-3

P.Ramesh, Assistant Professor, AIML Dept, 24


TKREC
OOP through Java UNIT-3
New: - When a thread object is created using new, then the thread is said to be in the New
state. This state is also known as Born state.
Ex: - Thread t1=new Thread();

Runnable / Ready: - When a thread calls start( ) method, then the thread is said to be in the
Runnable state. This state is also known as a Ready state.
Ex: - t1.start();

Running:- When a thread calls run( ) method, then the thread is said to be Running. The
run( ) method of a thread called automatically by the start( ) method.

Blocked / Waiting: - A thread in the Running state may move into the blocked state due to
various reasons like sleep( ) method called, wait( ) method called, suspend( ) method called,
and join( ) method called, etc.

When a thread is in the blocked or waiting state, it may move to Runnable state due to
reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method
called, resume( ) method called, etc.

Ex: -
Thread.sleep(100);
Wait();
Suspened();
Notify();
notifyAll();
resume();

Dead / Terminated: - A thread in the Running state may move into the dead state due to
either its execution completed or the stop( ) method called. The dead state is also known as
the terminated state.

Creating threads
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.

The java programming language provides two methods to create threads, and they are listed
below.
 Using Thread class (by extending Thread class)
 Using Runnable interface (by implementing Runnable interface)

Extending Thread class: - The java contains a built-in class Thread inside the java.lang
package. The Thread class contains all the methods that are related to the threads.

To create a thread using Thread class, follow the step given below.
 Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
P.Ramesh, Assistant Professor, AIML Dept, 25
TKREC
OOP through Java UNIT-3
 Step-4: Call the start( ) method on the object created in the above step.

Example: -

// Creating Thread by using Extending Thread class

class MyThread extends Thread


{
public void run()
{
for(int i= 1; i<10; i++)
{
System.out.println(" Child Thread");
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
MyThread t = new MyThread();
System.out.println("Thread about to start...");
t.start();
for(int i= 1; i<10; i++)
{
System.out.println(" Main Thread");
}
}
}
OUTPUT: -
D:\TKREC\Java>java ThreadDemo
Thread about to start...
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread

P.Ramesh, Assistant Professor, AIML Dept, 26


TKREC
OOP through Java UNIT-3
// Creating Thread by using Extending Thread class

class SampleThread extends Thread


{
public void run()
{
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
System.out.println("i = " + i);
}
}
}
public class ThreadDemo1
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

OUTPUT: -

D:\TKREC\Java>java ThreadDemo1
Thread about to start...
Thread is under Running...
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10

Implementing Runnable interface: - The java contains a built-in interface Runnable inside
the java.lang package. The Runnable interface implemented by the Thread class that contains
all the methods that are related to the threads.

To create a thread using Runnable interface, follow the step given below.
 Step-1: Create a class that implements Runnable interface.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter
to the Thread class constructor.

P.Ramesh, Assistant Professor, AIML Dept, 27


TKREC
OOP through Java UNIT-3
 Step-5: Call the start( ) method on the Thread class object created in the above step.

Example: -

// Creating Thread by Implementing Runnable Interface

class SampleThread extends Thread


{
public void run()
{
System.out.println("Thread is under Running...");
for(int i= 1; i<=5; i++)
{
System.out.println("i = " + i);
}
}
}
public class ThreadRunnableInterface
{
public static void main(String[] args)
{
SampleThread threadObject = new SampleThread();
Thread t2 = new Thread(threadObject);
System.out.println("Thread about to start...");
t2.start();
}
}
OUTPUT: -
D:\TKREC\Java>java ThreadRunnableInterface
Thread about to start...
Thread is under Running...
i=1
i=2
i=3
i=4
i=5

// Creating Multiple Threads

class MyThread implements Runnable


{
String name;
Thread t;
MyThread (String thread)
{
name = thread;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}

P.Ramesh, Assistant Professor, AIML Dept, 28


TKREC
OOP through Java UNIT-3
// Overriding run() method
public void run() {
try {
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
// Let the thread sleep for a while.
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThread
{
public static void main(String args[])
{
new MyThread("One");
new MyThread("Two");
new MyThread("Three");
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
OUTPUT: -
D:\TKREC\Java>java MultiThread
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Three: 5
Two: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2

P.Ramesh, Assistant Professor, AIML Dept, 29


TKREC
OOP through Java UNIT-3
One: 1
Two: 1
Three: 1
One exiting.
Three exiting.
Two exiting.
Main thread exiting.

// CurrentThread class Demo

class CurrentThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
OUTPUT: -
D:\TKREC\Java>java CurrentThread
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1

Interrupting threads
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the
interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.

P.Ramesh, Assistant Professor, AIML Dept, 30


TKREC
OOP through Java UNIT-3
The 3 methods provided by the Thread class for interrupting a thread
 public void interrupt()
 public static boolean interrupted()
 public Boolean isInterrupted()

Example of interrupting a thread that stops working: - After interrupting the thread, we
are propagating it, so it will stop working. If we don't want to stop the thread, we can handle
it where sleep() or wait() method is invoked. Let's first see the example where we are
propagating the exception

// interrupting a Thread that stops working

class InterruptingThreadDemo extends Thread


{
public void run() {
try {
Thread.sleep(1000);
System.out.println("task");
}
catch(InterruptedException e) {
throw new RuntimeException("Thread interrupted..."+e);
}
}

public static void main(String args[]) {


InterruptingThreadDemo t1=new InterruptingThreadDemo ();
t1.start();
t1.interrupt();
}
}
OUTPUT: -
D:\TKREC\Java>java InterruptingThreadDemo
Exception in thread "Thread-0" java.lang.RuntimeException: Thread
interrupted...java.lang.InterruptedException: sleep interrupted
at InterruptingThreadDemo.run(InterruptingThreadDemo.java:15)

Example of interrupting a thread that doesn’t stops working: - After interrupting the
thread, we handle the exception, so it will break out the sleeping but will not stop working.

// interrupting a Thread that doesn't stop working

class NoInterruptingThreadDemo extends Thread


{
public void run() {
try {
Thread.sleep(1000);
System.out.println("task");
}
catch(InterruptedException e) {
System.out.println("Exception handled "+e);

P.Ramesh, Assistant Professor, AIML Dept, 31


TKREC
OOP through Java UNIT-3
}
System.out.println("thread is running...");
}

public static void main(String args[])


{
NoInterruptingThreadDemo t1=new NoInterruptingThreadDemo();
t1.start();
t1.interrupt();
}
}
OUTPUT: -
D:\TKREC\Java>java NoInterruptingThreadDemo
Exception handled java.lang.InterruptedException: sleep interrupted
thread is running...

Thread Priority
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java,
the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and
priority 10 is considered as the highest priority. The thread with more priority allocates the
processor first.

The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and
they are listed below.
 MAX_PRIORITY - It has the value 10 and indicates highest priority.
 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority.

NOTE: - The default priority of any thread is 5 i.e NORM_PRIORITY

setPriority( ) method: - The setPriority( ) method of Thread class used to set the priority of
a thread. It takes an integer range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.

Example: - threadObject.setPriority(4); (or) threadObject.setPriority(MAX_PRORITY);

getPriority( ) method:- The getPriority( ) method of Thread class used to access the
priority of a thread. It does not takes any argument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.

Example:-
String threadName = threadObject.getPriority();

Note: In java, it is not guaranteed that threads execute according to their prority because it
depends on JVM specification that which scheduling it chooses
P.Ramesh, Assistant Professor, AIML Dept, 32
TKREC
OOP through Java UNIT-3

// Thread Priority
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " + Thread.currentThread().getName());
}
}
public class ThreadProrityDemo
{
public static void main(String[] args)
{
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.start();
threadObject2.start();
}
}
OUTPUT: -
D:\TKREC\Java>java ThreadProrityDemo
Inside SampleThread
Inside SampleThread
Current Thread: first
Current Thread: second

// MultiThread Priority
class MultiThreadPriority extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
}
class ThreadPriorityDemo1
{
public static void main(String args[])
{
MultiThreadPriority m1=new MultiThreadPriority ();
MultiThreadPriority m2=new MultiThreadPriority ();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}

P.Ramesh, Assistant Professor, AIML Dept, 33


TKREC
OOP through Java UNIT-3
}
OUTPUT: -
D:\TKREC\Java>java ThreadPriorityDemo1
running thread name is:Thread-1
running thread name is:Thread-0
running thread priority is:10
running thread priority is:1

Synchronizing Threads (or) Thread 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.

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

Synchronization is used to solve data inconsistency problem. It is the modifier


applicable only for methods and blocks. Can’t apply for classes and Variables.

Synchronized keyword in java creates a block of code as critical section, to enter a critical
section a thread needs to obtain the corresponding objects Lock.

// Example of java synchronized method

class Table
{
//synchronized method
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

P.Ramesh, Assistant Professor, AIML Dept, 34


TKREC
OOP through Java UNIT-3
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

public class SynchronizationDemo


{
public static void main(String args[])
{
//only one object
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
OUTPUT: -
D:\TKREC\Java>java SynchronizationDemo
5
10
15
20
25
100
200
300
400
500

// A Java program to demonstrate working of synchronized.

import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender
{
public void send(String msg)
{
System.out.println("Sending\t” + msg );
System.out.println("\n" + msg + "Sent");

P.Ramesh, Assistant Professor, AIML Dept, 35


TKREC
OOP through Java UNIT-3
}
}
// Class for send a message using Threads
class MyThread extends Thread
{
private String msg;
Sender sender;

// Receives a message object and a string message to be sent


MyThread(String m, Sender obj)
{
msg = m;
sender = obj;
}
public void run()
{
// Only one thread can send a message at a time.
synchronized(sender)
{
// synchronizing the snd object
sender.send(msg);
}
}
}

// Driver class
class SynchronizationDemo1
{
public static void main(String args[])
{
Sender snd = new Sender();
MyThread S1 = new MyThread( " Hi " , snd );
MyThread S2 = new MyThread( " Bye " , snd );

// Start two threads of ThreadedSend type


S1.start();
S2.start();
}
}

OUTPUT: -
D:\TKREC\Java>java SynchronizationDemo1
Sending Hi

Hi Sent
Sending Bye

Bye Sent

P.Ramesh, Assistant Professor, AIML Dept, 36


TKREC
OOP through Java UNIT-3
INTER-THREAD COMMUNICATION IN JAVA

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:


 wait()
 notify()
 notifyAll()

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
public final void wait()throws waits until object is notified.
InterruptedException
public final void wait(long Waits for the specified amount of time
timeout)throws InterruptedException

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

notifyAll() method:- Wakes up all threads that are waiting on this object's monitor.

Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication

P.Ramesh, Assistant Professor, AIML Dept, 37


TKREC
OOP through Java UNIT-3
The point to point explanation of the above diagram is as follows:
 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits the monitor state of
the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class? It
is because they are related to lock and object has a lock.

Difference between wait and sleep

The important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock
wait() method is the method of Object sleep() method is the method of Thread
class class
wait() method is the non-static method sleep() method is the static method
wait() method should be notified by sleep() method after the specified
notify() or notifyAll() methods amount of time, sleep is completed

// Example of inter thread communication in java

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount) {
System.out.println("Less balance; waiting for deposit...");
}
this.amount-=amount;
System.out.println("going to deposit...");
}
synchronized void deposit(int amount)
{
System.out.println("deposit completed... ");
this.amount+=amount;
System.out.println("withdraw completed...");
notify();
}
}
class InterThreadCommunicationDemo
P.Ramesh, Assistant Professor, AIML Dept, 38
TKREC
OOP through Java UNIT-3
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}
.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}
.start();
}
}
OUTPUT: -
D:\TKREC\Java>java InterThreadCommunicationDemo
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...

// Example of inter thread communication in java

public class InterThreadCommunication


{
public static void main(String[] args) throws InterruptedException
{
ThreadB b = new ThreadB();
b.start();
synchronized (b)
{
System.out.println("main thread calling wait() method"); // step 1
b.wait();
System.out.println("main thread got notification call"); // step 4
System.out.println("totol balance " + b.totalBalance);
}
}
}
class ThreadB extends Thread
{
int totalBalance = 0;

P.Ramesh, Assistant Professor, AIML Dept, 39


TKREC
OOP through Java UNIT-3
public void run()
{
synchronized (this)
{
System.out.println("child Thread starts calculation for total balance"); // step 2
for (int i = 0; i <= 50; i++)
{
totalBalance = totalBalance + i;
}
System.out.println("child thread gives notification call"); // step 3
this.notify();
}
}
}
OUTPUT: -
D:\TKREC\Java>java InterThreadCommunication
main thread calling wait() method
child Thread starts calculation for total balance
child thread gives notification call
main thread got notification call
totol balance 1275

Thread groups
Java provides a convenient way to group multiple threads in a single object. In such a way,
we can suspend, resume or interrupt a group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by java.lang.ThreadGroup class.


 A ThreadGroup represents a set of threads.
 A thread group can also include the other thread group.
 The thread group creates a tree in which every thread group except the initial thread
group has a parent.

A thread is allowed to access information about its own thread group, but it cannot access
the information about its thread group's parent thread group or any other thread groups.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.

Constructor Description
ThreadGroup(String name) Creates a thread group with given name.
ThreadGroup(ThreadGroup Creates a thread group with a given parent
parent, String name) group and name.

A code to group multiple threads


ThreadGroup tg1 = new ThreadGroup("Group A");
Thread t1 = new Thread(tg1,new MyRunnable(),"one");
Thread t2 = new Thread(tg1,new MyRunnable(),"two");

P.Ramesh, Assistant Professor, AIML Dept, 40


TKREC
OOP through Java UNIT-3
Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is
the class that implements Runnable interface and "one", "two" and "three" are the thread
names.

Now we can interrupt all threads by a single line of code only.


Thread.currentThread().getThreadGroup().interrupt();

// Threadgroup Example

public class ThreadGroupDemo implements Runnable


{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo obj = new ThreadGroupDemo();
ThreadGroup tg = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg, obj ,"one");


t1.start();
Thread t2 = new Thread(tg, obj ,"two");
t2.start();
Thread t3 = new Thread(tg, obj ,"three");
t3.start();

System.out.println("Thread Group Name: "+tg.getName());


tg.list();
}
}
OUTPUT: -
D:\Java>java ThreadGroupDemo
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]

Daemon threads.
Daemon thread in Java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically. There are many java daemon threads running
automatically e.g. gc, finalizer etc.

The jconsole tool provides information about the loaded classes, memory usage, running
threads etc.

P.Ramesh, Assistant Professor, AIML Dept, 41


TKREC
OOP through Java UNIT-3
Points to remember for Daemon Thread in Java
 It provides services to user threads for background supporting tasks. It has no role in
life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class

The java.lang.Thread class provides two methods for java daemon thread.

 public void setDaemon(boolean status):- is used to mark the current thread as


daemon thread or user thread.
 public boolean isDaemon():- is used to check that current is daemon.

// Simple example of Daemon thread in java

public class TestDaemonThread extends Thread


{
public void run()
{
if(Thread.currentThread().isDaemon())
{
//checking for daemon thread
System.out.println("daemon thread work");
}
else
{
System.out.println("user thread work");
}
}
public static void main(String[] args)
{
//creating thread
TestDaemonThread t1=new TestDaemonThread();
TestDaemonThread t2=new TestDaemonThread();
TestDaemonThread t3=new TestDaemonThread();

//now t1 is daemon thread


t1.setDaemon(true);

//starting threads
t1.start();
t2.start();
t3.start();
}

P.Ramesh, Assistant Professor, AIML Dept, 42


TKREC
OOP through Java UNIT-3
}
OUTPUT: -
D:\Java>java TestDaemonThread
daemon thread work
user thread work
user thread work

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.

class TestDaemonThread2 extends Thread


{
public void run()
{
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}

public static void main(String[] args)


{
TestDaemonThread2 t1=new TestDaemonThread2();
TestDaemonThread2 t2=new TestDaemonThread2();
t1.start();

//will throw exception here


t1.setDaemon(true);
t2.start();
}
}
OUTPUT: -
D:\Java>java TestDaemonThread2
Exception in thread "main" java.lang.IllegalThreadStateException
Name: Thread-0
Daemon: false
at java.base/java.lang.Thread.setDaemon(Thread.java:1400)
at TestDaemonThread2.main(TestDaemonThread2.java:16)

Enumerations
An enumeration is a list of named constants. Java enumerations appear similar to
enumerations in other languages.

In java, an Enum(short for enumeration) is a special data type in Java that contains a fixed
set of constants. Enum is a special kind of class that extends the java.lang.Enum class.
Enums allow us to know all the possible values for a field at the compile-time and make our
code more readable. We can use them to avoid undesirable behavior due to invalid inputs.

For example, an enum of directions can only have four possible values - north, south, east,
and west.

In java, the enumeration concept was defined based on the class concept. When

P.Ramesh, Assistant Professor, AIML Dept, 43


TKREC
OOP through Java UNIT-3
we create an enum in java, it converts into a class type. This concept enables
the java enum to have constructors, methods, and instance variables.

All the constants of an enum are public, static, and final. As they are static, we
can access directly using enum name.

The main objective of enum is to define our own data types in Java, and they
are said to be enumeration data types.

Creating enum in Java


 An enumeration is created by specifying the constant values that it can have.
 We use the enum keyword to create an enumeration in Java. All the enum constants
must be written in capital letters (NORTH, not north).
 All enum constants are static and final. Static allows us to access the constants by
using the name of the enum.

The syntax for creating enum is similar to that of class.

In java, an enum can be defined outside a class, inside a class, but not inside a
method.

// Example for An enumeration of apple varieties.

enum Apple
{
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}

Let's look at the following example program for creating a basic enum.

enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumerationExample


{
public static void main(String[] args)
{
WeekDay day = WeekDay.FRIDAY;
System.out.println("Today is " + day);
System.out.println("\n All WeekDays: ");
for(WeekDay d:WeekDay.values())
System.out.println(d);
}
}
OUTPUT:
D:\TKREC\Java>java EnumerationExample
Today is FRIDAY

P.Ramesh, Assistant Professor, AIML Dept, 44


TKREC
OOP through Java UNIT-3
All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY

 Every enum is converted to a class that extends the built-in class Enum.
 Every constant of an enum is defined as an object.

As an enum represents a class, it can have methods, constructors. It also


gets a few extra methods from the Enum class, and one of them is the values()
method.
Constructors in Java enum
In a java programming language, an enum can have both the type of
constructors defaultand parameterized. The execution of constructor depends on
the constants we defined in the enum. For every constant in an enum, the
constructor is executed. If an enum has a parameterized constructor, the
parameter value should be passed whenwe define constant.

Let's look at the following example program for illustrating constructors in


enum.

enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");

String msg;

WeekDay()
{
System.out.println("Default constructor!");
}

WeekDay(String str)
{
System.out.println("\n Parameterized constructor!");
msg = str;
}
}

public class EnumerationExampleConstructors


{
public static void main(String[] args)
{
WeekDay day = WeekDay.SUNDAY;
System.out.println("\n Today is " + day + " and its " + day.msg);

P.Ramesh, Assistant Professor, AIML Dept, 45


TKREC
OOP through Java UNIT-3
}
}
OUTPUT:
D:\TKREC\Java>java EnumerationExampleConstructors
Default constructor!
Default constructor!
Default constructor!
Default constructor!
Default constructor!
Default constructor!

Parameterized constructor!

Today is SUNDAY and its Holiday

In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other constants created by calling default constructor.

Methods in Java enum


All enumerations automatically contain two predefined methods: values( ) and valueOf( ).
Their general forms are shown here
 public static enum-type[ ] values( )
 public static enum-type valueOf(String str)
The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to the
string passed in str

The following program demonstrates the values( ) and valueOf( ) methods:


// Use the built-in enumeration methods.
// An enumeration of apple varieties.
enum Apple
{
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}

class EnumDemo
{
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");

// use values() method


Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();

// use valueOf() method


ap = Apple.valueOf("Winesap");

P.Ramesh, Assistant Professor, AIML Dept, 46


TKREC
OOP through Java UNIT-3
System.out.println("ap contains " + ap);
}
}
OUTPUT:
D:\Java>java EnumDemo
Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland

ap contains Winesap

 In java, enum cannot extend another enum and a class.


 In java, enum can implement interfaces.
 In java, enum does not allow to create an object of it.
 In java, every enum extends a built-in class Enum by default.

Autoboxing
In java, all the primitive data types have defined using the class concept, these
classes known as wrapper classes. In java, every primitive type has its
corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.

The following table shows the primitive type and its corresponding wrapper
class.

S.No Primitive Wrapper class


. Type
1 byte Byte

2 short Short

3 int Integer

4 long Long

5 float Float

6 double Double

7 char Character

8 boolean Boolean

The Java 1.5 version introduced a concept that converts primitive type to
corresponding wrapper type and reverses of it.

P.Ramesh, Assistant Professor, AIML Dept, 47


TKREC
OOP through Java UNIT-3

Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding
wrapperclass object is called autoboxing or simply boxing.

The compiler automatically performs the autoboxing when a primitive type value
has assigned to an object of the corresponding wrapper class.

We can also perform autoboxing manually using the method valueOf( ), which
is provided by every wrapper class.

Let's look at the following example program for autoboxing.

import java.lang.*;

public class AutoBoxingExample


{
public static void main(String[] args)
{
// Auto boxing: primitive to Wrapper
int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("Number = " + num + ", i = " + i + ", j = " + j);
}
}
OUTPUT:
D:\TKREC\Java>java AutoBoxingExample
Number = 100, i = 100, j = 100

Auto un-boxing in Java


In java, the process of converting an object of a wrapper class type to a primitive
typevalue is called auto un-boxing or simply unboxing.

The compiler automatically performs the auto un-boxing when a wrapper


class objecthas assigned to a primitive type.

We can also perform auto un-boxing manually using the method intValue( ),
which is provided by Integer wrapper class. Similarly every wrapper class has a
method for auto un-boxing.

Let's look at the following example program for auto un-boxing.

import java.lang.*;

public class AutoUnboxingExample


{
public static void main(String[] args)
{
// Auto un-boxing: Wrapper to primitive

P.Ramesh, Assistant Professor, AIML Dept, 48


TKREC
OOP through Java UNIT-3
Integer num = 200;
int i = num;
int j = num.intValue();

System.out.println("Number = " + num + ", i = " + i + ", j = " + j);


}
}
OUTPUT:
D:\TKREC\Java>java AutoUnboxingExample
Number = 200, i = 200, j = 200

Annotations
An annotation is created through a mechanism based on the interface.

For example here is the declaration for an annotation called MyAnno


// A simple annotation type.
@interface MyAnno
{
String str();
int val();
}
First, notice the @ that precedes the keyword interface. This tells the compiler that an
annotation type is being declared. Next, notice the two members str( ) and val( ).

An annotation cannot include extends clause. However, all annotation types automatically
extend the Annotation interface. Thus, Annotation is a super-interface of all annotations. It
is declared within the java.lang.annotation package. It overrides hashCode( ), equals( ),
and toString( ), which are defined by Object. It also specifies annotationType( ), which
returns a Class object that represents the invoking annotation

Here is a program that assembles all of the pieces shown earlier and uses reflection to
display the annotation associated with a method.

// Example

import java.lang.annotation.*;
import java.lang.reflect.*;

// An annotation type declaration.


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno
{
String str();
int val();
}
class Meta
{
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth()
P.Ramesh, Assistant Professor, AIML Dept, 49
TKREC
OOP through Java UNIT-3
{
Meta ob = new Meta();
// Obtain the annotation for this method and display the values of the members.
try
{
// First, get a Class object that represents this class.
Class c = ob.getClass();

// Now, get a Method object that represents this method.


Method m = c.getMethod("myMeth");

// Next, get the annotation for this class.


MyAnno anno = m.getAnnotation(MyAnno.class);

// Finally, display the values.


System.out.println(anno.str() + " " + anno.val());
}
catch (NoSuchMethodException e)
{
System.out.println("Method Not Found.");
}
}
public static void main(String args[])
{
myMeth();
}
}
OUTPUT:
D:\Java>java Meta
Annotation Example 100

Generics
The java generic is a language feature that allows creating methods and class which
can handle any type of data values. The generic programming is a way to write
generalized programs, java supports it by java generics.

The java generic is similar to the templates in the C++ programming language.
Most of the collection framework classes are generic classes.
The java generics allows only non-primitive type, it does not support primitive
typeslike int, float, char, etc.

The java generics feature was introduced in Java 1.5 version. In java, generics
usedangular brackets “< >”.

In java, the generics feature implemented using the following.


 Generic Method
 Generic Class

Generic methods in Java


The java generics allow creating generic methods which can work with a different
P.Ramesh, Assistant Professor, AIML Dept, 50
TKREC
OOP through Java UNIT-3
type of data values. Using a generic method, we can create a single method that
can be called with arguments of different types. Based on the types of the
arguments passed to the generic method, the compiler handles each method call
appropriately.

Just like classes, methods in Java can also take a type parameter. This will enable us to use
the same method for different object types.

Consider the code below, which uses a Generic print() method to print an object. <T> in the
method definition, tells Java that this is a Generic method with parameter type T. We can use
this type T anywhere in the method implementation. The diamond operator must be used
even if the method returns void.

Example - Generic method

public class GenericsDemo


{
public static <T> void print(T object)
{
System.out.println(object);
}

public static void main(String[] args)


{
String s = "100";
Integer i = 100;
Double d = 100.0;

print(s);
print(i);
print(d);
}
}

OUTPUT:
D:\TKREC\Java>java GenericsDemo
100
100
100.0

Generic methods can also take multiple type parameters

Example - Generic method

import java.util.ArrayList;
import java.util.LinkedList;

public class GenericsDemoMethods


{
public static <T, E> void printLists(ArrayList<T> l1, LinkedList<E> l2)

P.Ramesh, Assistant Professor, AIML Dept, 51


TKREC
OOP through Java UNIT-3
{
System.out.println(l1);
System.out.println(l2);
}

public static void main(String[] args)


{
ArrayList<Integer> al = new ArrayList<>();
al.add(5);
al.add(10);
al.add(15);

LinkedList<String> ll = new LinkedList<>();


ll.add("five");
ll.add("ten");
ll.add("fifteen");
printLists(al, ll);
}
}
OUTPUT:
D:\TKREC\Java>java GenericsDemoMethods
[5, 10, 15]
[five, ten, fifteen]

Generic Class in Java


In java, a class can be defined as a generic class that allows creating a class
that canwork with different types.

A generic class declaration looks like a non-generic class declaration, except that
theclass name is followed by a type parameter section.

Syntax for creating an Object of a Generic type


Class_name <data type> reference_name = new Class_name<data type> ();
OR
Class_name <data type> reference_name = new Class_name<>();

This is also known as Diamond Notation of creating an object of Generic type.

Let's look at the following example program for generic class.

Example - Generic class

//<> brackets indicates that the class is of generic type


class Gen <T>
{
T ob; //an object of type T is declared<
Gen(T o) //constructor
{
ob = o;
}

P.Ramesh, Assistant Professor, AIML Dept, 52


TKREC
OOP through Java UNIT-3
public T getOb()
{
return ob;
}
}

class GenericDemoClass
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance of Integer type Gen Class
int x = iob.getOb();
System.out.println(x);
Gen < String> sob = new Gen<>("Hello"); //instance of String type Gen Class
String str = sob.getOb();
System.out.println(str);
}
}
OUTPUT:
D:\TKREC\Java>java GenericDemoClass
100
Hello

P.Ramesh, Assistant Professor, AIML Dept, 53


TKREC

You might also like