Java Exception Handling & Multithreading
Java Exception Handling & Multithreading
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in
Exceptions – User defined Exception. Multithreaded Programming: Java Thread Model–Creating
a Thread and Multiple Threads – Priorities – Synchronization – Inter Thread Communication-
Suspending –Resuming, and Stopping Threads –Multithreading. Wrappers – Auto boxing.
Exception in Java is an indication of some unusual event. Usually it indicates the error. Let us
first understand the concept. In Java, exception is handled, using five keywords try, catch, throw,
throws and finally.
• Exception in Java is an indication of some unusual event. Usually it indicates the error. Let us
first understand the concept. In Java, exception is handled, using five keywords try, catch, throw,
throws and finally.
• The Java code that you may think may produce exception is placed within the try block. Let .
us see one simple program in which the use of try and catch is done in order to handle the
exception divide by zero.
class ExceptionDemo
try
int a,b;
a=5;
b=a/0;
}
catch(ArithmeticException e)
[Link]("Divide by Zero\n");
Output
Divide by Zero
Inside a try block as soon as the statement: b=a/0 gets executed then an arithmetic exception
must be raised, this exception is caught by a catch block. Thus there must be a try-catch pair and
catch block should be immediate follower of try statement. After execution of catch block the
control must come on the next line. These are basically the exceptions thrown by java runtime
systems.
1. Using exception the main application logic can be separated out from the code which may
cause some unusual conditions.
2. When calling method encounters some error then the exception can be thrown. This avoids
crashing of the entire application abruptly.
3. The working code and the error handling code can be separated out due to exception handling
mechanism. Using exception handling, various types of errors in the source code can be grouped
together.
4. Due to exception handling mechanism, the errors can be propagated up the method call stack
i.e. problems occurring at the lower level can be handled by the higher up methods.
Exception Hierarchy
The exception hierarchy is derived from the base class Throwable. The Throwable class is
further divided into two classes - Exceptions and Errors.
Exceptions: Exceptions are thrown if any kind of unusual condition occurs that can be caught.
Sometimes it also happens that the exception could not be caught and the program may get
terminated.
Errors: When any kind of serious problem occurs which could not be handled easily like
OutOfMemoryError then an error is thrown.
Types of Exception
For example: IOException which should be handled using the try-catch block.
o Unchecked Exception: These type of exceptions need not be handled explicitly. The Java
Virtual Machine handles these type of exceptions. These exceptions are extended from
[Link] class.
catch - The catch block handles the specific type of exception along with the try block. Note that
for each corresponding try block there exists the catch block.
finally - It specifies the code that must be executed even though exception may or may not
Occur.
throw - This keyword is used to throw specific exception from the program code.
Review Question
[Link] the exception hierarchy in java and explain with examples throwing and catching
exceptions and the common exception.
4. Explain the different types of exceptions and the exception hierarchy in java with appropriate
examples.
The statements that are likely to cause an exception are enclosed within a try block. For these
statements the exception is thrown.
try-catch Block
• The statements that are likely to cause an exception are enclosed within a try block. For these
statements the exception is thrown.
• There is another block defined by the keyword catch which is responsible for handling the
exception thrown by the try block.
try
catch(Type_of_Exception e)
• If any one statement in the try block generates exception then remaining statements are skipped
and the control is then transferred to the catch statement.
Java Program[[Link]]
class RunErrDemo
{
int a,b,c;
a=10;
b=0;
try
c=a/b;
catch(ArithmeticException e)
Output
Divide by zero
The value of a: 10
The value of b: 0
Note that even if the exception occurs at some point, the program does not stop at that point.
It is not possible for the try block to throw a single exception [Link] may be the situations
in which different exceptions may get raised by a single try block statements and depending upon
the type of exception thrown it must be caught.
• It is not possible for the try block to throw a single exception always.
• There may be the situations in which different exceptions may get raised by a single try block
statements and depending upon the type of exception thrown it must be caught.
• To handle such situation multiple catch blocks may exist for the single try block statements.
try
...//exception occurs
catch(Exception_type e)
catch (Exception_type e)
}
catch(Exception_type e)
Example
Java Program[[Link]]
class MultipleCatchDemo
try
a[i] = i *i;
a[i] = i/i;
}
catch (ArrayIndexOutOfBoundsException e)
catch (ArithmeticException e)
Output
Note: If we comment the first for loop in the try block and then execute the above code we will
get following output
• When there are chances of occurring multiple exceptions of different types by the same set of
statements then such situation can be handled using the nested try statements.
Java Program[[Link]]
class NestedtryDemo
try
int ans = 0;
try
ans = a/b;
catch (ArithmeticException e)
[Link]("Divide by zero");
catch (NumberFormatException e)
}
Output
D:\>javac [Link]
D:\>java NestedtryDemo 20 10
The result is 2
D:\>java NestedtryDemo 20 a
D:\>java NestedtryDemo 20 0
Divide by zero
Sometimes because of execution of try block the execution gets break off. And due to this some
important code (which comes after throwing off an exception) may not get executed. That
Using finally
• Sometimes because of execution of try block the execution gets break off. And due to this some
important code (which comes after throwing off an exception) may not get executed. That
means, sometimes try block: may bring some unwanted things to happen.
• The finally block provides the assurance of execution of some important code that must be
executed after the try block.
• Even though there is any exception in the try block the statements assured by finally block are
sure to execute. These statements are sometimes called as clean up code. The syntax of finally
block is
finally {
The finally block always executes. The finally block is to free the resources.
/*
This is a java program which shows the use of finally block for handling exception */
class finallyDemo
int a 10,b=-1;
try
b=a/0;
catch(ArithmeticException e)
finally
if(b!= -1)
else
}
}
Output
Program Explanation
• In above program, on occurrence of exception in try block the control goes to catch block, the
exception of instance ArithmeticException gets caught. This is divide by zero exception and
therefore /by zero will be printed as output. Following are the rules for using try, catch and
finally block
1. There should be some preceding try block for catch or finally block. Only catch block or only
finally block without preceding try block is not at all possible.
2. There can be zero or more catch blocks for each try block but there must be single finally
block present at the end.
When a method wants to throw an exception then keyword throws is used. Let us understand this
exception handling mechanism with the help of simple Java program.
Using throws
• When a method wants to throw an exception then keyword throws is used. The syntax is
• Let us understand this exception handling mechanism with the help of simple Java program.
Java Program
*/
class ExceptionThrows
{
int c;
try
c=a/b;
catch(ArithmeticException e)
int a=5;
fun(a,0);
Output
• In above program the method fun is for handling the exception divide by zero. This is an
arithmetic exception hence we write
static void fun(int a,int b) throws ArithmeticException
• This method should be of static type. Also note as this method is responsible for handling the
exception the try-catch block should be within fun.
For explicitly throwing the exception, the keyword throw is used. The keyword throw is
normally used within a method. We can not throw multiple exceptions using throw.
Using throw
• For explicitly throwing the exception, the keyword throw is used. The keyword throw is
normally used within a method. We can not throw multiple exceptions using throw.
int c;
if(b==0)
else
c=a/b;
int a=5;
fun(a,0);
}
}
Output
at [Link]([Link])
at [Link]([Link])
• Various common exception types and causes are enlisted in the following table-
Review Question
We can throw our own exceptions using the keyword [Link] the Throwable's subclass is
actually a subclass derived from the Exception class.
For example -
Throwable's subclass
Java Program[[Link]]
import [Link];
MyOwnException(String msg)
super(msg);
class MyExceptDemo
int age;
age=15;
try
{
if(age<21)
catch (MyOwnException e)
[Link] ([Link]());
finally
Output
Program Explanation
• In above code, the age value is 15 and in the try block exception if the value is less than 21. As
soon as the exception is thrown the catch block gets executed. Hence as an output we get the first
message "This is My Exception block". Then the control is transferred to the class
MyOwnException(defined at the top of the program). The message is set and it is "Your age is
very less than the condition". This message can then printed by the catch block using the
[Link] statement by means of [Link].
• At the end the finally block gets executed.
Ex. 3.9.1: Write an exception class for a time of day that can accept only 24 hour
representation of clock hours. Write a java program to input various formats of timings
and throw suitable error messages.
Sol.:
import [Link];
import [Link].*;
import [Link].*;
MyException(String msg)
super(msg);
class Clock
String h=[Link]();
String m=[Link]();
hour=[Link](h);
minute= [Link](m);
try
[Link]("Hour: "+hour);
catch(MyException e)
[Link]([Link]());
try
[Link]("Minute: "+minute);
}
catch(MyException e)
[Link]([Link]());
class ClockDemo
[Link]();
Output(Run1)
25:80
Hour: 25
Minute: 80
Output(Run2)
Enter the time in hh:mm format
10:70
Hour: 10
Minute: 70
Output(Run3)
30:40
Hour: 30
Minute: 40
Review Question
What is Thread ?
• One of the exciting features of Windows operating system is that - It allows the user to handle
multiple tasks together. This facility in Windows operating system is called multitasking.
• In Java we can write the programs that perform multitasking using the multithreading concept.
Thus Java allows to have multiple control flows in a single program by means of multithreading.
Review Question
Thread is life cycle specifies how a thread gets processed in the Java program. By executing
various methods. Following figure represents how a particular thread can be in one of the state at
any time.
Java Thread Model
Thread is life cycle specifies how a thread gets processed in the Java program. By executing
various methods. Following figure represents how a particular thread can be in one of the state at
any time.
New state
• When a thread starts its life cycle it enters in the new state or a create state.
Runnable state
• Waiting state
• Sometimes one thread has to undergo in waiting state because another thread starts executing.
• There is a provision to keep a particular threading waiting for some time interval. This allows
to execute high prioritized threads first. After the timing gets over, the thread in waiting state
enters in runnable state.
Blocked state
• When a particular thread issues an Input/Output request then operating system sends it in
blocked state until the I/O operation gets completed. After the I/O completion the thread is sent
back to the runnable state.
Terminated state
After successful completion of the execution the thread in runnable state enters the terminated
state.
Review Questions
In Java we can implement the thread programs using two approaches - Using Thread class, sing
runnable interface.
Creating a Thread
As given in Fig. 3.12.1, there are two methods by which we can write the Java thread programs
one is by extending thread class and the other is by implementing the Runnable interface.
• The run() method is the most important method in any threading program. By using this
method the thread's behaviour can be implemented. The run method can be written as follows -
For invoking the thread's run method the object of a thread is required. This object can be
obtained by creating and initiating a thread using the start() method.
• Using the extend keyword your class extends the Thread class for creation of thread. For
example if I have a class named A then it can be written as
• Constructor of Thread Class: Following are various syntaxes used for writing the constructor of
Thread Class.
Thread()
Thread(String s)
• Various commonly used methods during thread programming are as given below -
Following program shows how to create a single thread by extending Thread Class,
Java Program
[Link]("Thread is created!!!");
class ThreadProg
[Link]();
}
Output
Program Explanation :
In above program, we have created two classes. One class named MyThread extends the Thread
class. In this class the run method is defined. This run method is called by [Link]() in main()
method of class ThreadProg.
The thread gets created and executes by displaying the message Thread is created.
Ex. 3.12.1: Create a thread by extending the Thread Class. Also make use of constructor
and display message "You are Welcome to Thread Programming".
Sol.:
MyThread(String s)//constructor
[Link]=s;
}
public void run()
[Link](str);
class ThreadProg
Output
1. If a class extends a thread class then it can not extends any other class which may be required
to extend.
2. If a class thread is extended then all its functionalities get inherited. This is an expensive
[Link]
• Following Java program shows how to implement Runnable interface for creating a single
thread.
Java Program
[Link]("Thread is created!");
[Link]();
Output
Program Explanation :
4. The start method in-turn calls the run method written in MyClass.
• The run method executes and display the message for thread creation.
Ex. 3.12.2 Create a thread by extending the Thread Class. Also make use of constructor
and display message "You are Welcome to Thread Programming".
Sol. :
String str;
MyThread(String s)
{
[Link]=s;
[Link](str);
class ThreadProgRunn
[Link]();
Output
Ex. 3.12.3: Write a Java program that prints the numbers from 1 to 10 line by line after
every 10 seconds.
Sol. :
Java Program[[Link]]
class NumPrint extends Thread
int num;
NumPrint()
try
for(int i=1;i<=10;i++)
[Link](i);
catch (InterruptedException e)
}
}
NumPrint t1;
t1=new NumPrint();
Output
C:>javac [Link]
C:>java MultiThNum
9
10
Review Questions
[Link] is meant by concurrent programming? Define thread. Discuss the two ways of
implementing thread using example.
The multiple threads can be created both by extending Thread class and by implementing the
Runnable interface.
Multithreading
The multiple threads can be created both by extending Thread class and by implementing the
Runnable interface.
for(int i=0;i<=5;i++)//printing 0 to 5
[Link](i);
for(int i=10;i>=5;i--)//printing 10 to 5
[Link](i);
class ThreadProg
A t1=new A();
B t2=new B();
[Link]();
[Link]();
Output
1
2
10
2. Java Program for creating multiple threads by implementing the Runnable interface
for(int i=0;i<=5;i++)//printing 0 to 5
[Link](i);
for(int i=10;i>=5;i--)//printing 10 to 5
[Link](i);
A obj1=new A();
B obj2=new B();
[Link]();
[Link]();
Output
0
10
5.
Ex. 3.13.1: Write a Java application program for generating four threads to perform the
following operations - i) Getting N numbers as input ii) Printing the numbers divisible by
five iii) Printing prime numbers iv) Computing the average.
Sol. :
import [Link].*;
import [Link].*;
int i;
[Link]("\nGenerating Numbers: ");
for (i=1;i<=10;i++)
[Link](i);
int i;
if (i%5==0)
[Link](i);
{
public void run() //generating the prime numbers
int i;
int j;
int n = i%j;
if (n==0)
break;
if(i == j)
[Link](i);
{
int i,sum;
double avg;
sum=0;
sum=sum+i;
avg=sum/(i-1);
[Link](avg);
class MainThread
Output
Generating Numbers:
10
Divisible by Five:
10
Computing Average:
5.0
Prime Numbers:
3
5
Ex. 3.13.2: Create a Bank Database application program to illustrate the use of
multithreads
Sol. :
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]();
[Link]()
[Link]();
makeWithdrawal(10);
if ([Link]() < 0) {
[Link]("Account Overdrawn!!!");
int bal;
bal [Link]();
[Link]("\t"+[Link]().getName()+withdraws Rs."+amt);
try {
[Link](100);
[Link](amt);
[Link]();
} else {
class Account {
private int balance 100;
return balance;
Review Questions
1. What is multithreading? What are the methods available in Java for inter-thread
communication? Discuss with example
4. Write a java application that illustrate the use of multithreading. Explain the same with sample
input.
5. Describe the creation of a single thread and multiple threads using an example
[Link] a simple real life application program in Java to illustrate the use of multithreads.
• In Java threads scheduler selects the threads using their prioritie• The thread priority is a simple
integer value that can be assigned to the particular [Link] priorities can range from 1
(lowest priority) to 10 (highest priority).
Priorities
• The thread priority is a simple integer value that can be assigned to the particular thread.
o getPriority
Thread_Name.setPriority (priority_val);
Where, priority_val is a constant value denoting the priority for the thread. It is defined as
follows
1. MAX_PRIORITY = 10
2. MIN_PRIORITY = 1
3. NORM_PRIORITY = 5
Thread_Name.getPriority();
What is Preemption?
• Preemption is a situation in which when the currently executed thread is suspended temporarily
by the highest priority thread.
• The highest priority thread always preempts the lowest priority thread.
Let us see the illustration of thread prioritizing with the help of following example
Java program[Thread_PR_Prog.java]
[Link]("Thread #1");
for(int i=1;i<=5;i++)
{
[Link]("\tA: "+i)
[Link]("Thread #2");
for(int k=1;k<=5;k++)
[Link]("\tB: "+k);
class Thread_PR_Prog
{
A obj1=new A();
B obj2=new B();
[Link](1);
[Link](10);//highest priority
[Link]("Strating Thread#1");
[Link]();
[Link]("Strating Thread#2");
[Link]();
Output
Strating Thread #1
Strating Thread#2
Thread #1
Thread #2
B: 1
B: 2
B: 3
B: 4
B: 5
A: 2
A: 3
A: 4
A: 5
Program explanation
In above program,
3) In the main function both the threads are started but as the Thread #2 has higher priority than
the Thread#1, the Thread #2 preempts the execution of Thread#1.
When two or more threads need to access shared memory, then there is some way to ensure that
the access to the resource will be by only one thread at a time.
Synchronization
• When two or more threads need to access shared memory, then there is some way to ensure
that the access to the resource will be by only one thread at a time. The process of ensuring one
access at a time by one thread is called synchronization. The synchronization is the concept
which is based on monitor. Monitor is used as mutually exclusive lock or mutex. When a thread
owns this monitor at a time then the other threads can not access the resources. Other threads
have to be there in waiting state.
• In Java every object has implicit monitor associated with it. For entering in object's monitor, the
method is associated with a keyword synchronized. When a particular method is in synchronized
state then all other threads have to be there in waiting state.
class Test
[Link](" "+num*i);
[Link]("\nEnd of Table");
try
[Link](1000);
}catch(Exception e){}
Test th1;
A(Test t)
th1=t;
}
[Link](2);
Test th2;
B(Test t)
th2=t;
[Link](100);
class MySynThread
{
Test obj=new Test();
A t1=new A(obj);
B t2=new B(obj);
[Link]();
[Link]();
Output
Program Explanation:
• In above program we have written one class named Test. Inside this class the synchronized
method named display is written. This method displays the table of numbers.
• We have written two more classes named A and B for executing the thread. The constructors
for class A and Class B are written and to initialize the instance variables of class Test as th1 (as
a variable for class A)and th2(as a variable for class B)
• Inside the run methods of these classes we have passed number 2 and 10 respectively and
display method is invoked.
• The display method executes firstly for thread t1 and then for t2 in synchronized manner.
• When we want to achieve synchronization using the synchronized block then create a block of
code and mark it as synchronized.
• Synchronized statements must specify the object that provides the intrinsic lock.
Syntax
synchronized(object reference)
statement;
Java Program
class Test
Synchronized(this)
[Link](“ ”+num*i);
try
[Link] (1000);
} catch(Exception e){}
Test th1;
A(Test t)
th1=t;
[Link](2);
}
}
Test th2;
B(Test t)
th2=t;
[Link](100);
class MySynThreadBlock
A t1=new A(obj);
B t2=new B(obj);
[Link]();
[Link]();
}
Output
1. Only methods can be synchronized but the variables and classes can not be synchronized.
3. A class contains several methods and all methods need not be synchronized.
4. If two threads in a class wants to execute synchronized methods and both the methods are
using the same instance of a class then only one thread can access the synchronized method at a
time.
Review Questions
• Two or more threads communicate with each other by exchanging the messages. This
mechanism is called interthread communication.
• But there are situations in which the producer has to wait for the consumer to finish consuming
of data. Similarly the consumer may need to wait for the producer to produce the data.
• In Polling system either consumer will waste many CPU cycles when waiting for producer to
produce or the producer will waste CPU cycles when waiting for the consumer to consume the
data.
• In order to avoid polling there are three in-built methods that take part in inter-thread
communication -
Example Program
Following is a simple Java program in which two threads are created one for producer and
The producer thread produces(writes) the numbers from 0 to 9 and the consumer thread
consumes(reads) these numbers.
The wait and notify methods are used to send particular thread to sleep or to resume the thread
from sleep mode respectively.
Java Program[[Link]]
class MyClass
int val;
synchronized int get() //by toggling the flag synchronised read and write is performed
if(!flag)
try
wait();
catch (InterruptedException e)
[Link]("InterruptedException!!!");
flag = false;
notify();
return val;
if(flag)
try
wait();
catch (InterruptedException e)
[Link]("InterruptedException!!!");
[Link] = val;
flag = true;
notify();
MyClass th1;
Producer(MyClass t).
th1 = t;
}
for(int i =0;i<10;i++)
[Link](i);
MyClass th2;
Consumer(MyClass t)
th2 = t;
for(int I = 0;i<10;i++)
[Link]();
}
}
class InterThread
[Link]();
[Link]();
Output
Producer producing 0
Consumer consuming: 0
Producer producing 1
Consumer consuming: 1
Producer producing 2
Consumer consuming: 2
Producer producing 3
Consumer consuming: 3
Producer producing 4
Consumer consuming: 4
Producer producing 5
Consumer consuming: 5
Producer producing 6
Consumer consuming: 6
Producer producing 7
Consumer consuming: 7
Producer producing 8
Consumer consuming: 8
Producer producing 9
Consumer consuming: 9
Program Explanation
• Inside get() -
The wait() is called in order to suspend the execution by that time the producer writes the value
and when the data gets ready it notifies other thread that the data is now ready. Similarly when
the consumer reads the data execution inside get() is suspended. After the data has been
obtained, get() calls notify(). This tells producer that now the producer can write the next data in
the queue.
• Inside put() -
The wait() suspends execution by that time the consumer removes the item from the queue.
When execution resumes, the next item of data is put in the queue, and notify() is called. When
the notify is issued the consumer can now remove the corresponding item for reading.
Stopping a thread: A thread can be stopped from running further by issuing the following
statement - [Link]();
[Link]();
By this statement the thread enters in a dead state. From stopping state a thread can never return
to a runnable state.
‘• Blocking a thread: A thread can be temporarily stopped from running. This is called blocking
or suspending of a thread. Following are the ways by which thread can be blocked
1. sleep()
By sleep method a thread can be blocked for some specific time. When the specified time gets
elapsed then the thread can return to a runnable state.
2. suspend
By suspend method the thread can be blocked until further request comes. When the resume()
method is invoked then the thread returns to a runnable state.
3. wait
The thread can be made suspended for some specific conditions. When the notify method is
called then the blocked thread returns to the runnable state.
• The difference between the suspending and stopping thread is that if a thread is suspended
then its execution is stopped temporarily and it can return to a runnable state. But in case, if a
thread is stopped then it goes to a dead state and can never return to runnable state.
Resuming a thread: The resume() method is only used with suspend() method. This method is
only to resume a thread which was suspended using suspend() method. The syntax is -
Ex. 3.17.1 Write a java program for inventory problem to illustrates the usage of thread
synchronized keyword and inter thread communication process. They have three classes
called consumer, producer and stock.
Sol.:
class Consumer implements Runnable
Stock obj1;
Thread t;
this.obj1 = obj1;
[Link]();
while (true)
try {
[Link](900);
} catch (InterruptedException e) { }
[Link]((int)([Link]()*100));
void stop()
{
[Link]();
Stock obj2;
Thread t;
Producer(Stock obj2)
this.obj2 = obj2;
[Link]();
while(true)
try {
[Link](900);
} catch (InterruptedException e) { }
[Link]((int)([Link]()*100));
}
}
void stop()
[Link]();
class Stock
int items = 0;
items = items + i;
notify();
while(true)
if(items >= i)
{
items = items - j;
break;
else
try {
wait();
}catch(InterruptedException e) { }
return items;
try
{
[Link](10000);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Thread stopped");
} catch (InterruptedException e) { }
[Link](0);
}
Wrapper classes are those classes that allow primitive data types to be accessed as objects. The
wrapper class is one kind of wrapper around a primitive data type.
Wrappers
• Wrapper classes are those classes that allow primitive data types to be accessed as objects.
• The wrapper class is one kind of wrapper around a primitive data type. The wrapper classes
represent the primitive data types in its instance of the class.
• Following table shows various primitive data types and the corresponding wrapper classes -
• Methods to handle wrapper classes are enlisted in the following table -
• Suppose an object for holding an integer value is created then we can retrieve the integer value
from it using typevalue() method. For instance the object obj contains an integer value then we
can obtain the integer value from obj. It is as follows -
int num=[Link]();
str=[Link](int_val)
• For converting the string to numerical value the parseInt or parseLong methods can be used.
3. After assigning the values to the wrapper class we cannot change them.
import [Link].*;
import [Link].*;
class WrapperDemo
String str="100";
}
}
Output
Ex. 3.18.1Define wrapper class. Give the following wrapper class methods with
class WrapperDemo1
int i=100;
String str=[Link](i);
int j= [Link](str);
[Link]("String: "+str);
Integer a new Integer(1000);//creating object for float value int val [Link]();
[Link]("Integer: "+a);
float f=[Link]();
[Link]("Float: "+b);
Output
String: 500
Integer: 1000
Float: 2000.0
1) Wrapper classes are used to convert numeric strings into numeric values.
2) Wrapper classes are used to convert numeric value to string using wrapper class.
4) Using the typeValue() method we can retrieve value of the object as its primitive data type.
Review Questions
An automatic conversion of primitive data type into equivalent wrapper type is called as
autoboxing.
Autoboxing
Definition: An automatic conversion of primitive data type into equivalent wrapper type is
called as autoboxing.
Example Program
class AutoboxExample
//unboxing
Output
Program Explanation
In above program,
(2) Then using the byteValue() method we are unboxing this value. This method converts the
given number into a primitive byte type and returns the value of integer object as byte.
(3) Finally we are displaying both the object value and primitive value.