Java Unit-3
Java Unit-3
EXCEPTION HANDLING
Definition:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
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:
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
Example Program:1
import java.io.*;
class sample
System.out.println(fileInput.readLine());
file.close();
4
Output
import java.io.*;
System.out.println(fileInput.readLine());
fileInput.close();
5
Output
2) Unchecked Exception
Example Program
class Example
int arr[]={1,2,3,4,5}
System.out.println(arr[7]);
Output:
6
3) Error
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.
7
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
There are given some scenarios where unchecked exceptions may occur. They are
as follows:
int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
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
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.
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
9
The catch block must be used after the try block only.
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:
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.
Output:
11
Java finally block
Definition:
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.
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");
}
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.
14
Example 1
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:
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:
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:
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.
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:
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:
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:
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:
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..
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.
24
Example program:
Output
Caught
Hello
MULTITHREADING
Definition:
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.
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
26
Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area.
27
executing thread object.
28
19) Void interrupt() It interrupts the thread.
21) static boolean interrupted() It tests whether the current thread has
been interrupted.
29
30) String toString() It is used to return a string
representation of this thread,
including the thread's name, priority,
and thread group.
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.
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.
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
It represents the runnable state.It means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a
lock.
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
Example Program
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
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:
2) Running
3) Suspended
4) Blocked
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
37
CREATE A THREAD IN JAVA
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.
Runnable interface:
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
39
Multi t1=new Multi();
t1.start();
}
}
40
}
41
public final int getPriority():
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
Output:
SYNCHRONIZATION
44
2. To prevent consistency problem.
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:
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.
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
If we put all the codes of the method in the synchronized block, it will work
same as the synchronized 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
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.
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.
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
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
The block synchronizes on the lock of the object denoted by the reference .class
name .class.
INTER-THREAD COMMUNICATION
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(long timeout)throws It waits for the specified amount of
InterruptedException time.
2) notify() method
Syntax:
Syntax:
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.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
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
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
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
The resume() method of thread class is only used with suspend() method.
Syntax
public final void resume()
Return value
Exception
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
Syntax
public final void stop()
public final void stop(Throwable obj)
Parameter
64
Return
Exception
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.
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.
boolean Boolean
char Character
byte Byte
Short Short
66
Int Integer
Long Long
Float Float
double Double
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
69