JPR Unit 4
JPR Unit 4
All the syntax errors are detected by Java compiler. These errors are called
compile-time errors.. Until and unless we clear compile compile-time
time errors from a
program, byte-code
code (.class file) will not be created for th that program. Some
examples of compile-time errors are semicolon missing, mismatch of braces, use of
undeclared variables etc.
After compiling a java program successfully, byte
byte-code
code (class file) is created.
Interpreter runs this class file. But even then sometimes the program generates
wrong output. This happens due to incorrect logic. This is called logical error (This
type of error is to be corrected by programmer by correcting the logic). Also,
sometimes program terminates due to errors like divide by zero. Both these
situations are referred to run-time errors. Some common run-time time errors are
divide by zero, accessing element which is out of bound of array, converting
invalid string to a number etc.
Exception is a condition caused due to occurrence of run run-time
time error. This
may be due to violation of rules of Java language or due to constraints of the java
execution environment. While executing a program, if exceptional condition (like
divide by zero) occurs, exception object is created by the java run-time
time system and
is thrown. Exception can also be generated manually by a program code.
In java, Throwable class woks as root for java’s error and exception
hierarchy as shown in following figure.
Throwable
Exception Error
try block
• Statements that cause exception
try
{
Statements that may generate/cause exception
}
catch(Exception-type obj-name)
{
Statements for processing the caught exception
}
We may write multiple statements (those may cause exception) in try block.
Multiple statements may also be written in catch block for handling the caught
exception.
As observed in the above syntax, catch block looks like a method accepting
one parameter. If this parameter matches with the thrown exception object,
statements in the catch block are executed. Otherwise default exception handler of
java run-time environment will terminate the program execution.
Example 1:
class Unit4_1
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
s = p / (q – r);
System.out.println(“Result is ”+s);
System.out.println(“At the end of try block”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block”);
}
System.out.println(“At the end of main method”);
}
}
Sample Output:
You should not divide a number by 0
At the end of catch block
At the end of main method
Example 2:
class Unit4_2
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i;
System.out.println(“Array elements are:”);
try
{
for(i=0;i<8;i++)
{
System.out.println(a[i]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
}
System.out.println(“Thank you for using this program”);
}
}
Sample Output:
Array elements are:
12
34
44
14
Accessing out of bound array element
Thank you for using this program
Example:
class Unit4_3
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i, p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
System.out.println(“Array elements are:”);
for(i=0;i<4;i++)
{
System.out.println(a[i]);
}
try
{
s = p / (q – r);
System.out.println(“Result is ”+s);
System.out.println(“At the end of try block 2”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block for try block 2”);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
System.out.println(“At the end of catch block for try block 1”);
}
System.out.println(“At the end of main method”);
}
}
Sample Output:
Array elements are:
12
34
44
14
You should not divide a number by 0
At the end of catch block for try block 2
At the end of main method
Example:
class Unit4_4
{
public static void main(String args[ ])
{
int a[]=new int[]{12,34,44,14};
int i, p, q, r;
p = 30;
q = 3;
r = 3;
try
{
a[5] = p / (q – r);
System.out.println(“Result of division is stored in array”);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by 0”);
System.out.println(“At the end of catch block 1”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Accessing out of bound array element”);
System.out.println(“At the end of catch block 2”);
}
System.out.println(“At the end of main method”);
}
}
Sample Output:
You should not divide a number by 0
At the end of catch block 1
At the end of main method
No Exception
occurred ?
Yes
No Exception
handled ?
Yes
finally block is
executed
Example:
class Unit4_5
{
static void method1(int x, int y)
{
int z;
try
{
z = x / y;
System.out.println(“Result of division is: ”+z);
}
catch(ArithmeticException e)
{
System.out.println(“You should not divide a number by zero”);
}
finally
{
System.out.println(“Finally block is always executed”);
}
}
Sample Output:
Result of division is: 2
Finally block is always executed
You should not divide a number by 0
Finally block is always executed
Following example programs show how we can create our own exception
and throw it.
Example 1:
class MyException1 extends Exception
{
MyException1(String message)
{
super(message);
}
}
class Unit4_6
{
public static void main(String args[ ])
{
try
{
throw new MyException1(“This is user-defined exception”);
}
catch(MyException1 e)
{
System.out.println(“Caught Exception”);
System.out.println(e.getMessage( ));
}
}
}
Sample Output:
Caught Exception
This is user-defined exception
Example 2:
import java.io.*;
class Employee
{
String name;
long salary;
Sample Output 1:
Enter name of employee:
Ajay
Enter salary of employee:
1200000
Name of employee: Ajay
Salary of employee: 1200000
Sample Output 2:
Enter name of employee:
Vijay
Enter salary of employee:
-250000
Caught Exception
Salary cannot be negative
Name of employee: Vijay
Salary of employee: 0
Example:
class Unit4_7
{
public static void main(String[] args)
{
try
{
NumberFormatException ex =
new NumberFormatException("Exception");
catch(NumberFormatException e)
{
// displaying the exception
System.out.println(e);
Sample Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception
Example:
class Unit4_8
{
static void method1( ) throws NullPointerException
{
System.out.println("In method1");
throw new NullPointerException("Demo");
}
-----
----
----------------
-----
--
--
--
----------
----
Start Start
Start
Example:
class MyThread1 extends Thread
{
public void run( )
{
int i;
System.out.println(“Starting MyThread1”);
for(i=1;i<=10;i++)
{
System.out.println(19*i); //Displays table of 19
}
System.out.println(“Exiting MyThread1”);
}
}
class Unit4_9
{
public static void main(String[] args)
{
int i;
System.out.println(“Starting main thread”);
MyThread1 mt1 = new MyThread1( );
mt1.start( );
for(i=2;i<=20;i=i+2)
{
System.out.println(i); //Displays even numbers
}
System.out.println(“Exiting main thread”);
}
}
Example:
class MyThread2 implements Runnable
{
public void run( )
{
int i;
System.out.println(“Starting MyThread2”);
for(i=10;i>=1;i--)
{
System.out.println(i*i*i); //Displays cubes from 10 to 1
}
System.out.println(“Exiting MyThread2”);
}
}
class Unit4_10
{
public static void main(String[] args)
{
int i;
System.out.println(“Starting main thread”);
MyThread2 mt = new MyThread2( );
Thread t = new Thread(mt);
t.start( );
for(i=19;i>=1;i=i-2)
{
System.out.println(i); //Displays odd numbers from 19 to 1
}
System.out.println(“Exiting main thread”);
}
}
suspend( ) resume( )
sleep( ) after specified time
stop( )
wait( ) notify( )
Blocked
Newborn State:
On creation, a thread enters in Newborn state. Thread in this state can
call start( ) method to become active. On calling start( ) method, run( ) method of
the thread is invoked automatically. Thread in this state may call stop( ) method
to enter in Dead state.
Runnable State:
Multiple threads may be in Runnable state. The threads in this state
are ready for execution and are waiting for availability of processor. (Processor can
run only one thread at an instance). Selection of a thread for allocation of
processor may be done on the basis of priority of the threads. If threads are having
same priority, threads may get selected on First Come First Serve basis.
Running State:
There can be only one thread in Running state at given instance of
time. Processor is allocated to such thread and it is being run by processor.
Running thread may invoke yield( ) method for giving control to another thread.
On invoking suspend( ) method, thread gets suspended. On invoking sleep(time)
method, thread sleeps for specified number of milliseconds. On invoking wait( )
method, threads goes in waiting. In all these cases, thread enters in Blocked state.
Blocked State:
When thread is prevented from entering in Runnable state, it is in
Blocked state. There are various reasons for entering this state. Thread may be
suspended, sleeping or waiting for being in this state. Suspended thread may
reenter in active state by invoking resume( ) method. Sleeping state will
automatically enter in active state on completion of sleeping time. Waiting state
may reenter in active state by invoking notify( ) method.
Dead State:
Thread may enter this state on its natural death. Thread in any state
may invoke stop( ) method for entering in this state.
}
}
}
System.out.println(“Exiting Thread 3”);
}
}
class Unit4_11
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );
Example:
class Thread1 extends Thread
{
public void run( )
{
int i;
for(i=0;i<10;i++)
{
System.out.println(“In thread 1, i = ” +i);
}
System.out.println(“Exiting Thread 1”);
}
}
class Unit4_12
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );
t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
4.2.5 Synchronization
System may have multiple threads. Such threads may require
communicating with each other. In such case, if the communicating threads are
not synchronized, strange results may be produced. i.e. it may happen that the
shared method may get called by different threads at the same time. To avoid this,
the method may be marked keyword synchronized as,
synchronized returntype methodname(arglist)
{
----
}
Because of this, java creates a monitor. This monitor allows a thread calling
this method first time to execute that method. No any other thread is able to enter
this method as long as first thread is executing this method.
4.2.6 Deadlock
If thread 1 is accessing method1( ) & wants to access method2( ), and the
same time thread 2 is accessing method2( ) & wants to access method1( ), this
situation is called deadlock.
notify( )
It resumes the first thread that went to sleep mode. Its syntax is as follows
final void notify( )
notifyall( )
It resumes all the threads those are in sleep mode. Its syntax is as follows
final void notifyall( )
wait( )
It sends the calling thread into sleep mode. This thread can come out of
sleep mode only by notify( ) method or notifyall( ) method. Its syntax is as follows
final void wait( )
Sample Questions:
1. Define error. List types of errors. [2M]
2. Name any four built in Exceptions in Java. [2M]
3. Define exception. State built-in exceptions. [4M]
4. Enlist any 4 keywords used for exception handling in Java. [2M]
5. Write the syntax of try-catch-finally blocks. [2M]
6. Describe types of Errors and Exceptions in details. [6M]
7. Write a program to input name and salary of employee and throw user
defined exception if entered salary is negative. [6M]
8. Explain the two ways of creating threads in Java. [4M]
9. Describe life cycle of thread with suitable diagram. [4M]
10. Describe methods of creating a thread with example. [4M]
11. Write a program to create two threads one thread will print even numbers
from 1 to 50 and other will print odd numbers between 1 and 50. [6M]
12. Write a program to create two threads. One thread will display the
numbers from 1 to 50 (ascending order) and other thread will display
numbers from 50 to 1 (descending order). [6M]
13. Write a program to define two threads for displaying even and odd numbers
respectively with a delay of 500 ms after each number. [6M]