Unit 3
Unit 3
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This will produce the following result −
Output
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number
of them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
class Excep1
{
public static void main(String args[])
{
int i=10;
try
{
i=i/Integer.parseInt(args[0]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(Exception e1)
{
System.out.println(e1);
}
System.out.println("Value of i=" +i);
}
}
OUTPUT
Program
class Excep6
{
public static void main(String args[])
{
try
{
System.out.println("going to divide");
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);
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Output
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 exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception. Using a finally block allows you to run
any cleanup-type statements that you want to execute, no matter what happens in the protected
code.
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Case 1
Let's see the java finally example where exception doesn't occur.
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 the code...");
}
}
Test it Now
Output:
5
finally block is always executed
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
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 the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
System.out.println("Testing Complete");
}
}
Output
Program
else
{
System.out.println("Welcome to vote");
}
}
public static void main(String args[])
{
try
{
validage(Integer.parseInt(args[0]));
}
catch(myexception my)
{
System.out.println(my);
}
System.out.println("Testing Complete");
}
}
Output
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important built -
in exceptions in Java.
3.4.1 Examples of Built-in Exception:
1. Arithmetic exception: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
// Java program to demonstrate
// ArithmeticException
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
2. 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.
System.out.print((char)i);
}
f.close();
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
// Java Program to illustrate
// InterruptedException
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
7. NoSuchMethodException : t is thrown when accessing a method which is not found.
// Java Program to illustrate
// NoSuchMethodException
class Geeks {
public Geeks()
{
Class i;
try {
i = Class.forName("java.lang.String");
try {
Class[] p = new Class[5];
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Geeks();
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the members of a
null object. Null represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
9. NumberFormatException : This exception is raised when a method could not convert
a string into a numeric format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate
that an index is either negative than the size of the string.
// Java program to demonstrate
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
myexception(String s)
super(s);
class Throws
if(age<18)
else
System.out.println("Welcome to vote");
try
validage(Integer.parseInt(args[0]));
catch(myexception my)
System.out.println(my);
System.out.println("Testing Complete");
OUTPUT
o A thread is lightweight.
o Cost of communication between the thread is low.
Note: At least one process is required for each thread
➢ A thread can be in one of the five states. The life cycle of the thread in java is controlled
by JVM. The java thread states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
New
➢ The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
Runnable
➢ The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
Running
➢ The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
➢ This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
➢ A thread is in terminated or dead state when its run() method exits.
o Creating more than one thread to perform multiple tasks is called multithreading
in Java. In multiple threading programming, multiple threads are executing
simultaneously that improves the performance of CPU because CPU is not idle
if other threads are waiting to get some resources.
o Multiple threads share the same address space in the heap memory. Therefore,
It is good to create multiple threads to execute multiple tasks rather than creating
multiple processes.
Example Program
// Two threads performing same tasks at a time.
//By implementing Runnable Interface
class MultiThread implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("thread running is "+i);
}
}
public static void main(String args[])
{
MultiThread m1=new MultiThread();
Thread t1 =new Thread(m1);
Thread t2= new Thread(m1);
Thread t3= new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
OUTPUT
3.8 PRIORITIES
➢ Thread priority in Java is a number assigned to a thread that is used by Thread scheduler
to decide which thread should be allowed to execute.
➢ In Java, each thread is assigned a different priority that will decide the order
(preference) in which it is scheduled for running.
➢ Thread priorities are represented by a number from 1 to 10 that specifies the relative
priority of one thread to another.
➢ The default priority of a thread is 5. Thread class in Java also provides several priority
constants to define the priority of a thread. These are:
1. MIN_PRIORITY = 1
2. NORM_PRIORITY = 5
3. MAX_PRIORTY = 10
➢ Thread scheduler selects the thread for execution on the first-come, first-serve basis.
That is, the threads having equal priorities share the processor time on the first -come
first-serve basis.
➢ When multiple threads are ready for execution, the highest priority thread is selected
and executed by JVM.
➢ In case when a high priority thread stops, or enters the blocked state, a low priority
thread starts executing.
➢ If any high priority thread enters the runnable state, it will preempt the currently running
thread forcing it to move to the runnable state. Note that the highest priority thread
always preempts any lower priority thread.
3.8.1 How to get Priority of Current Thread in Java?
• Thread class provides a method named getPriority() that is used to determine the
priority of a thread. It returns the priority of a thread through which it is called.
3.8.1.1 Let’s create a Java program in which we will determine the priority and name of
the current thread.
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");
System.out.println("Priority of Thread: " +t.getPriority());
System.out.println("Name of Thread: " +t.getName());
t.start();
}
}
OUTPUT
3.9 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.
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
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. Inter-thread communication
3.9.1 Mutual Exclusive
➢ Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
• by synchronized method
• by synchronized block
• by static synchronization
Concept of Lock in Java
➢ 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.
3.9.1.1 By synchronized method
• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
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);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
In this example we are applying synchronized keyword on the static method to perform static
synchronization.
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)
{}
}
}
}
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
9000
10000
Method Description
public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.
2) 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:
3) notifyAll() method
➢ Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
}
}
class Test
{
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
3.11 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.
➢ This method does not return any value.
3.11.1 Syntax
➢ public final void suspend()
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
t1.start();
t2.start();
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}
OUTPUT
import java.lang.*;
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //unboxing i.e converting Integer to int
int j=a; //auto unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
OUTPUT
3.14.2 AUTOBOXING