0% found this document useful (0 votes)
8 views69 pages

Java Unit-3

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views69 pages

Java Unit-3

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 69

Unit - 3

EXCEPTION HANDLING

Definition:

 The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that the normal flow of the application can
be maintained.
 In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Advantage 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 need to handle exceptions.

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10
will not be executed. However, when we perform exception handling, the rest of
the statements will be executed. That is why we use exception handling in Java.

Example Program:1

import java.util.Scanner;
class pre

1
{
public static void main(String args[])
{
int a,b,c;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException q)
{
System.out.println(q);
}
}
}

Output:

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception


hierarchy inherited by two subclasses:

Exception and Error.

2
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

3
Difference between Checked and Unchecked Exceptions
1) Checked Exception

 The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions.

 For example, IOException, SQLException, etc. Checked exceptions are


checked at compile-time.

Example Program:1

FileNotFoundException is a checked exception in Java. Anytime, we want to


read a file from the filesystem, Java forces us to handle an error situation where
the file may not be present in the place.

import java.io.*;

class sample

public static void main(String[] args)

FileReader file=new FileReader("F:\\test\\a.txt");

BufferedReader fileInput=new BufferedReader(file);

System.out.println(fileInput.readLine());

file.close();

4
Output

Same Example Program:

In this example the file.txt is created.

import java.io.*;

public class Main

public static void main(String[] args) throws IOException

FileReader file = new FileReader("D:\\TestFiles\\file.txt");

BufferedReader fileInput = new BufferedReader(file);

System.out.println(fileInput.readLine());

fileInput.close();

5
Output

2) Unchecked Exception

 The classes that inherit the RuntimeException are known as unchecked


exceptions.

 For example, ArithmeticException, NullPointerException,


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

Example Program

class Example

public static void main(String args[])

int arr[]={1,2,3,4,5}

System.out.println(arr[7]);

Output:

6
3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
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 necessary code of the program. It
is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throw The "throws" keyword is used to declare exceptions. It specifies that there
s may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

Java Exception Handling


Example Program

public class JavaExceptionExample


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

7
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are
as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

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


variable throws a NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException.

Suppose we have a string variable that has characters; converting this variable
into digit will cause NumberFormatException.

8
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException


occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block

Java try block


Definition:

 Java try block is used to enclose the code that might throw an exception.
It must be used within the method.

 If an exception occurs at the particular statement in the try block, the rest
of the block code will not execute. So, it is recommended not to keep the
code in try block that will not throw an exception.

 Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}

Java catch block


Definition:
 Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
 The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type.

9
 The catch block must be used after the try block only.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed which means try
block will throw an error to the catch block in which it executes.

Example 1
Problem without exception handling

10
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0;
System.out.println("rest of the code");
}
}

Output:

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.

Solution by exception handling


Example 2
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:

11
Java finally block

Definition:

 Java finally block is a block used to execute important code such as


closing the connection, etc.
 Java finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.
 The finally block follows the try-catch block.

Flowchart of finally block

Syntax of try-finally block

try
12
{
//code that may throw an exception
}
finally{}
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally


Case 1: When an exception does not occur

The below example where the Java program does not throw any exception, and
the finally block is executed after the try block.

Example Program:

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}

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


}
}

Output:

13
MULTIPLE CATCH CLAUSES

Definition:
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler.
So, have to perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

14
Example 1

public class MultipleCatchBlock1


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

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occu
rs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:

Arithmetic Exception occurs


rest of the code
Example 2:
public class MultipleCatchBlock2
{
public static void main(String[] args)
{
try{
int a[]=new int[5];

System.out.println(a[10]);
}

15
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is executed.

Example 3:
public class MultipleCatchBlock3
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}

16
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:

Arithmetic Exception occurs


rest of the code

NESTED TRY STATEMENT/NESTED TRY BLOCK


Nested try block
Definition:

In Java, using a try block inside another try block is permitted. It is called as nested
try block. Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.

Syntax:

try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
try
{
statement 5;

17
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
catch(Exception e3)
{
//exception message
}

Example 1
public class NestedTryBlock
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide by 0");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

18
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:

When any try block does not have a catch block for a particular exception, then
the catch block of the outer (parent) try block are checked for that exception,
and if it matches, the catch block of outer try block is executed.

If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then it
displays the system generated message for that exception.

Example 2
public class NestedTryBlock2
{
public static void main(String args[])
{
try
{
try
{
try
{
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
catch (ArithmeticException e)
{
19
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
catch (ArrayIndexOutOfBoundsException e4)
{
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5)
{
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}

Output:

BUILT-IN EXCEPTIONS IN JAVA


Definition:
 Built-in exceptions are the exceptions which are available in Java libraries.
 These exceptions are suitable to explain certain error situations.

Examples of Built-in Exception:

Arithmetic exception :
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
Example:

20
class ArithmeticException_Demo
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e)
{
System.out.println("Can't divide a number by 0");
}
}
}
Output:

Can't divide a number by 0


ArrayIndexOutOfBounds Exception :
It is thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the size of the
array.

Example:

class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];
a[6] = 9;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index is Out Of Bounds");
}
}
}

21
Output:

Array Index is Out Of Bounds

FileNotFoundException :
This Exception is raised when a file is not accessible or does not open.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
try {
File file = new File("E:// file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:

File does not exist

IOException :
It is thrown when an input-output operation failed or interrupted.

22
Example:
import java.io.*;
class sample
{
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1)
{
System.out.print((char)i);
}
f.close();
}
}

Output:
error: unreported exception IOException; must be caught or declared to be
thrown
NullPointerException :
This exception is raised when referring to the members of a null object. Null
represents nothing.
Example:
class NullPointer_Demo
{
public static void main(String args[])
{
try
{
String a = null;
System.out.println(a.charAt(0));
}
catch (NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}

23
Output:

NullPointerException..

USER-DEFINED CUSTOM EXCEPTION


Definition:
 Java user-defined exception is a custom exception created and throws that
exception using a keyword 'throw'.
 It is done by extending a class 'Exception'.
 An exception is a problem that arises during the execution of the
program.

An exception is an issue (run time error) that occurred during the execution of
a program. When an exception occurred the program gets terminated abruptly
and, the code past the line that generated the exception never gets executed.

Java provides us the facility to create our own exceptions which are basically
derived classes of Exception.
Creating our own Exception is known as a custom exception or user-defined
exception.
Basically, Java custom exceptions are used to customize the exception
according to user needs.
In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception
using the ‘throw’ keyword.

Why use custom exceptions?

 To catch and provide specific treatment to a subset of existing Java


exceptions.
 Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the developers
to understand the exact problem.

In order to create a custom exception, we need to extend the Exception class


that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception


which is obtained using the “getMessage()” function on the object created.

24
Example program:

class MyException extends Exception


{
public MyException(String s)
{
super(s);
}
}
public class Main
{
public static void main(String args[])
{
try
{
throw new MyException("Hello");
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}

Output

Caught
Hello

MULTITHREADING

Definition:

 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.

25
 However, we use multithreading than multiprocessing because threads
use a shared memory area.
 They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation, etc.

Advantages of java multithreading

1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) It can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


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

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

What is thread in java?

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


separate path of execution.

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

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.

JAVA THREAD METHODS

S.N. Modifier and Method Description


Type

1) Void start() It is used to start the execution of the


thread.

2) Void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified


amount of time.

4) static Thread currentThread() It returns a reference to the currently

27
executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) Long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing


thread object to pause and allow other
threads to execute temporarily.

13) Void suspend() It is used to suspend the thread.

14) Void resume() It is used to resume the suspended


thread.

15) Void stop() It is used to stop the thread.

16) Void destroy() It is used to destroy the thread group


and all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon


thread.

18) Void setDaemon() It marks the thread as daemon or user


thread.

28
19) Void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been


interrupted.

21) static boolean interrupted() It tests whether the current thread has
been interrupted.

22) static int activeCount() It returns the number of active threads


in the current thread's thread group.

23) void checkAccess() It determines if the currently running


thread has permission to modify the
thread.

24) static boolean holdLock() It returns true if and only if the


current thread holds the monitor lock
on the specified object.

25) static void dumpStack() It is used to print a stack trace of the


current thread to the standard error
stream.

26) StackTraceEleme getStackTrace() It returns an array of stack trace


nt[] elements representing the stack dump
of the thread.

27) static int enumerate() It is used to copy every active thread's


thread group and its subgroup into the
specified array.

28) Thread.State getState() It is used to return the state of the


thread.

29) ThreadGroup getThreadGroup() It is used to return the thread group to


which this thread belongs

29
30) String toString() It is used to return a string
representation of this thread,
including the thread's name, priority,
and thread group.

31) void notify() It is used to give the notification for


only one thread which is waiting for a
particular object.

32) void notifyAll() It is used to give the notification to all


waiting threads of a particular object.

33) void setContextClassLo It sets the context ClassLoader for the


ader() Thread.

34) ClassLoader getContextClassLo It returns the context ClassLoader for


ader() the thread.

35) static getDefaultUncaug It returns the default handler invoked


Thread.Uncaught htExceptionHandle when a thread abruptly terminates due
ExceptionHandle r() to an uncaught exception.
r

36) static void setDefaultUncaugh It sets the default handler invoked


tExceptionHandler when a thread abruptly terminates due
() to an uncaught exception.

LIFE CYCLE OF A THREAD (THREAD STATES)

In Java, a thread always exists in any one of the following states. These states
are:

1. New
2. Active
3. Blocked / Waiting

30
4. Timed Waiting
5. Terminated

New: Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not begun its
execution.

Active: When a thread invokes the start() method, it moves from the new state
to the active state. The active state contains two states within it: one
is runnable, and the other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable


state. In the runnable state, the thread may be running or may be ready to
run at any given instant of time. It is the duty of the thread scheduler to
provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to
each individual thread. Each and every thread runs for a short span of
time and when that allocated time slice is over, the thread voluntarily
gives up the CPU to the other thread, so that the other threads can also
run for their slice of time. Whenever such a scenario occurs, all those
threads that are willing to run, waiting for their turn to run, lie in the
runnable state. In the runnable state, there is a queue where the threads
lie.
o Running: When the thread gets the CPU, it moves from the runnable to
the running state. Generally, the most common change in the state of a
thread is from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not


permanently) then, either the thread is in the blocked state or is in the waiting
state.

Example

For example, a thread (let's say its name is A) may want to print some data from
the printer. However, at the same time, the other thread (let's say its name is B)
is using the printer to print some data. Therefore, thread A has to wait for thread
B to use the printer. Thus, thread A is in the blocked state. A thread in the
blocked state is unable to perform any execution and thus never consume any
cycle of the Central Processing Unit (CPU). Hence, we can say that thread A
remains idle until the thread scheduler reactivates thread A, which is in the
waiting or blocked state.

31
When the main thread invokes the join() method then, it is said that the main
thread is in the waiting state. The main thread then waits for the child threads to
complete their tasks. When the child threads complete their job, a notification is
sent to the main thread, which again moves the thread from waiting to the active
state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of
the thread scheduler to determine which thread to choose and which one to
reject, and the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a


thread (its name is A) has entered the critical section of a code and is not willing
to leave that critical section. In such a scenario, another thread (its name is B)
has to wait forever, which leads to starvation. To avoid such scenario, a timed
waiting state is given to thread B. Thus, thread lies in the waiting state for a
specific span of time, and not forever. A real example of timed waiting is when
we invoke the sleep() method on a specific thread. The sleep() method puts the
thread in the timed wait state. After the time runs out, the thread wakes up and
start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following


reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words,
the thread is dead, and there is no way one can respawn (active after kill) the
dead thread.

The following diagram shows the different states involved in the life cycle of a
thread.

32
Implementation of Thread States

In Java, one can get the current state of a thread using


the Thread.getState() method. The java.lang.Thread.State class of Java
provides the constants ENUM to represent the state of a thread. These constants
are:

public static final Thread.State NEW

It represents the first state of a thread that is the NEW state.

public static final Thread.State RUNNABLE

It represents the runnable state.It means a thread is waiting in the queue to run.

public static final Thread.State BLOCKED

It represents the blocked state. In this state, the thread is waiting to acquire a
lock.

public static final Thread.State WAITING

It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the
waiting state is waiting for another thread to complete its task.

33
public static final Thread.State TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and
timed waiting is the time constraint. Waiting has no time constraint, whereas
timed waiting has the time constraint. A thread invoking the following method
reaches the timed waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos

public static final Thread.State TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated


thread means it has completed its execution.

Java Program for Demonstrating Thread States

Example Program

class ABC implements Runnable


{
public void run()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}

System.out.println("The state of thread t1 while it invoked the


method join() on thread t2 -"+ ThreadState.t1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
34
ie.printStackTrace();
}
}
}
public class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;
public static void main(String argvs[])
{
obj = new ThreadState();
t1 = new Thread(obj);
System.out.println("The state of thread t1 after spawning it - " + t1.
getState());
t1.start();
System.out.println("The state of thread t1 after invoking the metho
d start() on it - " + t1.getState());
}
public void run()
{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);
System.out.println("The state of thread t2 after spawning it -
"+ t2.getState());
t2.start();
System.out.println("the state of thread t2 after calling the method st
art() on it - " + t2.getState());

try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 after invoking the metho
d sleep() on it - "+ t2.getState() );
try
{
t2.join();
}
catch (InterruptedException ie)

35
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it'
s execution - " + t2.getState());
}
}

Explanation:
Whenever we spawn a new thread, that thread attains the new state. When the
method start() is invoked on a thread, the thread scheduler moves that thread to the
runnable state. Whenever the join() method is invoked on any thread instance, the
current thread executing that statement has to wait for this thread to finish its
execution, i.e., move that thread to the terminated state. Therefore, before the final
print statement is printed on the console, the program invokes the method join() on
thread t2, making the thread t1 wait while the thread t2 finishes its execution and
thus, the thread t2 get to the terminated or dead state. Thread t1 goes to the waiting
state because it is waiting for thread t2 to finish it's execution as it has invoked the
method join() on thread t2.

Thread Model

A Thread is a very light-weighted process, or we can say the smallest part of


the process that allows a program to operate more efficiently by running
multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used the Thread


concept in Java. All the tasks are executed without affecting the main program.
In a program or process, all the threads have their own separate path for
execution, so each thread of a process is independent.

In a simple way, a Thread is a:

36
o Feature through which we can perform multiple activities within a single
process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run)

A thread is in New when it gets CPU time.

2) Running

A thread is in a Running state when it is under execution.

3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under


execution.

4) Blocked

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution
immediately.

37
CREATE A THREAD IN JAVA

A thread is created either by "creating or implementing" the Runnable


Interface or by extending the Thread class. These are the only two ways
through which we can create a thread.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations
on a thread.Thread class extends Object class and implements Runnable
interface.

Commonly used Constructors of Thread class:


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

Commonly used methods of Thread class:


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

Runnable interface:

The Runnable interface should be implemented by any class whose instances


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

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

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{

39
Multi t1=new Multi();
t1.start();
}
}

Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


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

Using the Thread Class: Thread(String Name)

public class MyThread1


{
public static void main(String argvs[])
{
Thread t= new Thread("My first thread");
t.start();
String str = t.getName();
System.out.println(str);
}

40
}

Using the Thread Class: Thread(Runnable r, String name)


public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[])
{
Runnable r1 = new MyThread2();
Thread th1 = new Thread(r1, "My new thread");
th1.start();
String str = th1.getName();
System.out.println(str);
}
}

PRIORITY OF A THREAD (THREAD PRIORITY)

 Each thread has a priority. Priorities are represented by a number between


1 and 10.
 In most cases, the thread scheduler schedules the threads according to
their priority (known as preemptive scheduling).
 But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.

Setter & Getter Method of Thread Priority

41
public final int getPriority():

The java.lang.Thread.getPriority() method returns the priority of the given


thread.

public final void setPriority(int newPriority):

The java.lang.Thread.setPriority() method updates or assign the priority of the


thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10
(maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example Program 1:
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());

42
System.out.println("Currently Executing The Thread : " + Thread.current
Thread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThr
ead().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThr
ead().getPriority());
}
}

Example Program 2:
import java.lang.*;
public class ThreadPriorityExample1 extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
Thread.currentThread().setPriority(7);
System.out.println("Priority of the main thread is : " + Thread.c
urrentThread().getPriority());
ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
System.out.println("Priority of the thread th1 is : " + th1.getPrio
rity());
}
}

43
Example Program of illegalArgumentException

We know that if the value of the parameter newPriority of the method


getPriority() goes out of the range (1 to 10), then we get the
IllegalArgumentException.
import java.lang.*;
public class IllegalArgumentException extends Thread
{
public static void main(String argvs[])
{
Thread.currentThread().setPriority(17);
System.out.println("Priority of the main thread is : " + Thread.curre
ntThread().getPriority());
}
}

Output:

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.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.

44
2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

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

Synchronized Method
Declaring 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.

45
Example Program:

class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}

46
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Synchronized Block

Synchronized block can be used to perform synchronization on any specific


resource of the method.

Suppose we have 50 lines of code in our method, but we want to synchronize


only 5 lines, in such cases, we can use synchronized block.

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

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


o Scope of synchronized block is smaller than the method.

47
o A Java synchronized block doesn't allow more than one JVM, to provide
access control to a shared resource.
o The system performance may degrade because of the slower working of
synchronized keyword.
o Java synchronized block is more efficient than Java synchronized
method.

Syntax

synchronized (object reference expression)


{
//code block
}

Example Program:

class Table
{
void printTable(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{

48
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

49
Static Synchronization

If you make any static method as synchronized, the lock will be on the class not
on object.

Problem without static synchronization

 Suppose there are two objects of a shared class (e.g. Table) named
object1 and object2.

50
 In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers
to a common object that have a single lock.

 But there can be interference between t1 and t3 or t2 and t4 because t1


acquires another lock and t3 acquires another lock.

 We don't want interference between t1 and t3 or t2 and t4. Static


synchronization solves this problem.

Example Program:
class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){}
}
}
}
class MyThread1 extends Thread
{
public void run()
{
Table.printTable(1);
}
}
class MyThread2 extends Thread
{
public void run()
{
Table.printTable(10);
}
}
class MyThread3 extends Thread
{
public void run()

51
{
Table.printTable(100);
}
}
class MyThread4 extends Thread
{
public void run()
{
Table.printTable(1000);
}
}
public class TestSynchronization4
{
public static void main(String t[])
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Output:

1
2
3
4
5
6
7
8
9
10
10
20
30
40

52
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Example of static synchronization by Using the anonymous class

class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){}
}
53
}
}
public class TestSynchronization5
{
public static void main(String[] args)
{
Thread t1=new Thread()
{
public void run()
{
Table.printTable(1);
}
};
Thread t2=new Thread()
{
public void run()
{
Table.printTable(10);
}
};
Thread t3=new Thread()
{
public void run()
{
Table.printTable(100);
}
};
Thread t4=new Thread()
{
public void run()
{
Table.printTable(1000);
}
};
t1.start();
t2.start();
t3.start();
t4.start();
}
}

54
Output:

1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000

55
9000
10000

Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class
name .class.

A static synchronized method printTable(int n) in class Table is equivalent to


the following declaration:

static void printTable(int n)


{
synchronized (Table.class)
{
// Synchronized block on class A
// ...
}
}

INTER-THREAD COMMUNICATION

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


synchronized threads to communicate with each other.

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


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

o wait()
o notify()
o notifyAll()

1) wait() method

The 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.

56
Method Description

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


InterruptedException

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

2) notify() method

 The notify() method wakes up a single thread that is waiting on this


object's monitor. If any threads are waiting on this object, one of them is
chosen to be awakened.

 The choice is arbitrary and occurs at the discretion of the implementation.

Syntax:

public final void notify()


3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()

Process of inter-thread communication

57
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.

Difference between wait and sleep

wait() sleep()

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

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or After the specified amount of time, sleep is


notifyAll() methods completed.

58
Output:

Example
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...");

try
{
wait();
}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test

59
{
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:

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

Java Thread suspend() method

 The suspend() method of thread class puts the thread from running to
waiting state.
 This method is used if you want to stop the thread execution and start it
again when a certain event occurs.
 This method allows a thread to temporarily cease execution.
 The suspended thread can be resumed using the resume() method.
Syntax
public final void suspend()
Return

This method does not return any value.


60
Exception

SecurityException: If the current thread cannot modify the thread.

Example Program:
public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
JavaSuspendExp t1=new JavaSuspendExp ();
JavaSuspendExp t2=new JavaSuspendExp ();
JavaSuspendExp t3=new JavaSuspendExp ();
t1.start();
t2.start();
t2.suspend();
t3.start();
}
}

61
Output

Java Thread resume() method

 The resume() method of thread class is only used with suspend() method.

 This method is used to resume a thread which was suspended using


suspend() method.

 This method allows the suspended thread to start again.

Syntax
public final void resume()
Return value

This method does not return any value.

Exception

SecurityException: If the current thread cannot modify the thread.

Example
public class JavaResumeExp extends Thread
{

62
public void run()
{
for(int i=1; i<5; i++)
{
try
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
JavaResumeExp t1=new JavaResumeExp ();
JavaResumeExp t2=new JavaResumeExp ();
JavaResumeExp t3=new JavaResumeExp ();
t1.start();
t2.start();
t2.suspend();
t3.start();
t2.resume();
}
}

63
Output

Java Thread stop() method

 The stop() method of thread class terminates the thread execution.

 Once a thread is stopped, it cannot be restarted by start() method.

Syntax
public final void stop()
public final void stop(Throwable obj)
Parameter

obj : The Throwable object to be thrown.

64
Return

This method does not return any value.

Exception

SecurityException: This exception throws if the current thread cannot modify


the thread.

Example
public class JavaStopExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
t1.start();
t2.start();
t3.stop();
System.out.println("Thread t3 is stopped");
} }

Output:

65
WRAPPER CLASSES

The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic conversion of
primitive into an object is known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with


objects many times like in Collections, Serialization, Synchronization, etc. Let
us see the different scenarios, where we need to use the wrapper classes.

o Change the value in Method: Java supports only call by value. So, if we
pass a primitive value, it will not change the original value. But, if we
convert the primitive value in an object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility classes to
deal with objects.
o Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

Short Short

66
Int Integer

Long Long

Float Float

double Double

Java Wrapper classes Example Program:

public class WrapperExample3


{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

System.out.println("---Printing object values---");


System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
67
System.out.println("Boolean object: "+boolobj);
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}
}

Output

AUTOBOXING

The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int
to Integer, long to Long, float to Float, boolean to Boolean, double to Double,
and short to Short.

68
Example Program

public class WrapperExample1


{
public static void main(String args[])
{
int a=20;
Integer i=Integer.valueOf(a); Integer j=a;
System.out.println(a+" "+i+" "+j);
}
}
Output

69

You might also like