0 ratings0% found this document useful (0 votes) 35 views38 pages4th Unit Java
4th unit of java from techknowledge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Exception Handling and
Multithreading
statement, throws and
= Errors and Exception : Types of errors, exceptions try and catch statement, nested try
Finally statement, build-in exceptions, chained exceptions, creating own exce'
Multithreaded Programming : Creating a Thread : By extending to thread class and by nein a
Interface. Life cycle of thread : Thread Methods : wait), sleep0. notify, resume(), ee ), stop
‘exceptions, thread priority and methods, synchronization, inter-thread communication, deadloc
jption, subclasses
programs concurrently. For example, process based
multitasking enables to run Java compiler at the same
time you can use the text editor. In the process based
multitasking, a program is a smallest unit of code that
‘can be dispatched by the scheduler. Process is
heavyweight task that requires their own address
spaces. Interprocess communication is expensive and
limited. Context switching from one process to
another process is costly. Java programs make the use
of process based multitasking environment, but the
Process-based multitasking is not under the control of
Java,
(S-12, W-13, 2 Marks)
thread with example. (W-12, 4 Marks)
(8-13, $-14, $-17, 2 Marks)|
— Java provides built in support for multithreaded
programming concept. A multithreaded program
‘contains two or more parts that can run concurrently.
ach part of program is called a thread and each thread
‘defines 2 separate path of execution. Thus,
‘multithreading is form of multitasking. For example a
Subprogram displaying animation while another is
‘building 2 animation next to be displayed. It is also
‘similar to dividing 2 task into subtasks and assigning
them differently for execution independently and
‘simultaneously,
~ Java programs we have seen, contains only a
sequential flow of control,
2. Thread based : In a thread based multitasking.
environment, the thread is the smallest unit of
dispatchable code. That means a single program can
Perform two or more task simultaneously. For an
instance, a text editor can format text at the same
time that is printing, as long as the two separate
threads are performing these two actions. Thus, the
Process based multitasking deals with’ “big picture”,
and the thread based multitasking handles the d
Multitasking thread réquires fewer overheads
© scanned with OKEN Scanner‘Multithreading refers
tan application with | to an application
‘multiple threads organised across
ding enables to write very. efficent Funning within a multiple 05-level
s that make maximum use ofthe CPU, bonne process. Multi threading | processes. Multi
. ss ns
2 nmin Tien ||| amcectng ema |
the interactive, networked environment rea ea
Java operates, because idle time is common, Cee ee. | eee
(Round robin processor | using more than one
time -sharing algorithm) | processor.
2. | Same job can be broken | Several jobs can run at
logically and executed | the same time.
simultaneously and the
results are combined at
the end of processing. |.
3. | The operating system | Multiprocessing means
can allow hundreds of | that you are using a
threads to be active, | computer that has
Fig. 4.4 regardless of the | mutiple processors
5 ; number of processors. | (cpus)
Java support multithreading is the unique ieisupen the opersting | ctor
erty of Java. That means, Java enables to use system to share. the
flows of control in program development. processor time among
flow of control may considered as a separate tiny various threads.
grams or module known as thread that runs in| [4 | Multithreading is the | When it comes to
elto others shown in Fig. 4.1.1(a). ability to perform Multiprocessing there
: different tasks of a will be more than one
s “ process simultaneously. | processor and each
This is achieved by using | thread will be handled
‘a separate thread for
each task.
Though there are
several threads in a
process, ata time the
© scanned with OKEN Scanner“mere ore actualy eworvPes OFSYSI0T™
” siasirvited tes + This SED ee i
approach ith polling.
? ‘event loop with polling. In this
model, nae eed of contol Uns in fn
foo, poling # single everit QUEUE 1D decide what
oto next. one this poling mechanism retums
wih signal, then the event loop dispatches
vantrolto the appropriate event handler until this
cont handler returns nothing can happen in
fystem results in wastage of CPU time. 1 fio
preults in dominating one part of program on
fystem and prevents other processes from being
processed, in this system, when a thread blocks
because itis waiting for other resources then the
entire program stops running.
I. Multithreaded system : In this environment the
= Muttithreaded programs main loop/polling mechanism is eliminated. One
: extends idea of multitasking Fee copie oa
re corre tea mace orem ed program. Multithreading allows the animation
: a pete ie Joops to sleep for a second between each frame
~ accel emaliat detiad without pausing the whole system to pause:
= er romani Oe ‘When thread blocks in Java program, only the
meer sean Inet RIY OF. single thread that is blocked pauses. All other
‘preventing the waste of CPU cycles. threads can continue to run.
A program that contains multiple flows of control is
Ctidnennasiiin |
‘Program is shown with four threads one main, and | 1-
‘other three. The main thread is actually main method | 2,
module which is designed to create and start the other
‘three threads A, B and C. Once initiated by main
‘thread, the threads A, 8, Crun concurrently and share | 3
“the resources jointly.
The ability of 2 language to support multithreads is
_melerred a5 concurrency, Since threads in Java are | 4 Threads are used in Java-enabled browsers such
ms of main application program and share Hotlava, a
memory space, they are known as light
ani
Itenables to do multiple things at the same time.
Long program can be divided into threads and’execute
them in parallel.
‘Speed of program is improved because the program |
divided into threads and threads are exect
‘concurrently.
© scanned with OKEN ScannerpT) ea
Ee Ste the ase: thread 1S felch
35 I performs various shutdown
the program starts its exec
d is created automatically but it
a thread object.
‘ution the main
‘can be controlled
control main() thread, get the referen
ing the method currentThread{). This m:
static member of Thread. Its syntax
ce to it by
jethod is the
= The above method in turns returns a reference to the
‘thread in which has been called. Now the main thread
“an object of type Thread. Java defines two ways in
Which this can be accomplished
“Implement runnable interface : First define a
lass that implements Runnable interface. The
Runnable interface contains only one method,
run( ). The run() method is defined in method
with the code to be executed by the thread.
Threads are implemented in form of objects that
* contain a method called run ). The run( ) method
makes up the entire body of thread and is the
‘only method in which the thread's behavior can
be implemented. A run( ) appears as follows :
The approach to be used can be decided according to
Fequirement like for what purpose the classes are
created. If it requires to extend another class, then
regardless but to implement the Runnable interface,
since Java classes cannot have two superciasses.
Threads are implemented in form of objects that
contain a method called run ).
4.1.3.1. Extending the Thread Class
|| — In this, to create a thread is to create new class that
‘extends Thread and then to create an instance of that
class.
= Extending the Thread class includes following steps :
1. Declare the class extending the Thread class.
‘The Thread class can be extended as follows :
‘The new type of MyFirstThread is created.
2. . Implement the run ( ) method that is responsible
for executing the sequence of code that the
thread with execute, The extending class must.
override the run() method, which is the entry
point of new thread. The run( ) method is
inherited by the class’ MyFirstThread. Now.
override this method in order to implement the
code to be executed by new thread
MyFirstThread. The implementation of run( )
be like : »
© scanned with OKEN Scanner"When new thread is started with start, Java calls
the threads run( ) method, so it is the runt )
where all the action takes place.
3, Create a thread object and call the start( )
method to initiate the thread execution.
Following statement creates new thread.
i. MyFirstThread T = new MyfirstThread{ );
‘Run instance of thread class or involve runt)
method.
Testart( };
With the i” statement thread object is just
created but not yet running meaning that it is
jin the new born state.
The ii® statement calls the start( ) method
‘causing the thread to move into runnable
state. Then, the Java runtime will schedule
the thread to run by invoking its run( )
method. Now the thread is said to be in the
running state.
Following Thread lass is used for creating and running
threads, which creates three threads A,B andC. *
Creating threads using the Thread class,
ts public void run ()
for Gntk = 13k <=5;k++)
ystem.out printin (“\t From
k= “tk);
}
System.out.printin ( “Exit from C“);
ot
S
lclass ThreadTest
ae *
public static void main (string args ()
tet
new X ().start () ;
new B ( ).start () ;
“new C().start () ;
© scanned with OKEN ScannerOutput of thread:
not specially sequentially or do not follow pa
order as they are running independently of one
"Y Bet a chance. So the
may produce different output from first one.
Implementing the ‘Runnable’ Interface
TESST
thread program for implementing the
interface’. (W-16, 5-18, 8 Marks)|
‘easiest way to create a thread is to create a class
at implements the Runnable interface. Runnable
facts a unit of executable code. Threads can be
iplementing the Runnable interface. The
interface declares the run () method that is
d for implementing threads in program. Follow
it run () method. [public void run() { })
that
thread defining an object
Scat “runnable” class as the
CoAane® 85 the inal value of object thread (wich s the
its rane) tte class). Whenever a new threadA starts UP:
target gyrate othe trgt abject supp to Here, te
(a Ue Object is runnable. if the direct reference to the
S ot required, then shortcut can be used. If the direct
reference to the thread thread A is not required, then
following ‘Shortcut can be used :
new Thread (new X()). start ();
Public void run ()
WM step 2
‘System.out.printin (“Thread A : a
}
‘System.out printin (“End of Thread A“);
© scanned with OKEN Scannertg
44.4 Stopping and Blocking a Thread
se
© scanned with OKEN Scannersdcan be stop,
statement causes to move to the dead
lea
d_will also move to the dead state
natically when it reaches the end of method
istop{ ) method can be used when the premature
ofa thread is required
jor suspended thread
d can be temporarily suspended or blocked
entering into the runnable and subsequently
ing state by using cither of following thread
thread is blocked for a specified time using
thread is blocked until further order for
ion of thread using suspend| }
‘thread is blocked until certain condition
irs by using wait( ).
we methods cause the thread to go into blocked or
tunable state.
are the methods with which the thread will
the runnable state : :
the specified time is elapsed in the case of
~The thread can enter into many states during its life
time. The five types of states are <
i. Newborn state ii, Runnable state
iii. Running state iv. Blocked state
v. Dead state.
Fig. 4.1.2 : Life cycle of thread
= _ The thread can be in one state from there five states
It can move from one state to another is variou:
shown in Fig. 4.1.2.
Newborn state
— When a thread object is created,
and called as thread is in :
iS Ways,
© scanned with OKEN ScannerFig. 4.1.3 : Scheduling a newborn thread
Runnable state
= The runnable state of a thread means that the thread
is ready for execution and is waiting for the availability
of the processor. The threads which are ready for
‘execution are placed in queue. So the runnable state
joins the queue of the threads that are waiting for
— fall threads have same priority, then they are given a
time slice for execution in round robin fashion, first-
‘come-first-serve manner. The thread after completing
its time slice joins the end of queue again waits for its
turn for execution. And this process of assigning time
to threads is known as time slicing.
— To release the control of thread to another thread to
equal priority before its turn comes, yield( ) method
‘can be used. Following Fig. 4.1.4 shows relinquishing
‘control using yield ( ) method.
‘i Yield
a ‘Running state means that the processor has given its
ne to the thread for its execution. The thread runs until it
| control on its own or itis preempted by higher
Sy method, which can be
led using suspended
: exivies to suspend a thread for some time but do
it shown in Fig. 4.1.5. 3
not want to kill
aged Runnable
Fig, 44.5 ; Releasing control using suspend () method
It can be made to sleep. The thread can be made to
sleep for a specified time period using the method,
sleep (time) where time is in miliseconds.
2
In this period the queue is out of ready queue. As soon,
as the time period is over the thread is re-entered in,
runnable state shown in Fig. 4.1.6.
Sleep(t)
o_o ©)
Running Runnable ‘Suspended
Fig. 4.1.6 : Releasing control using sleep () method
3. Thread is waiting until some event occurs and
wait( ) method is used to wait for condition, Using
notify() method thread can be scheduled to run again
shown in Fig. 4.1.7.
Wait é
Running Runnable Waiting
Fig. 4.1.7 : Releasing control using wait() method
Blocked state x
tis prevented from entering into the runnable
and subsequently the running state then itis said to
block state. It occurs wh
waiting
© scanned with OKEN Scanner_ Thread class methods can be used to contro! the
of the thread. In following program start( ),
}. yield, sleep stop| ) methods are used. Methods listed
The following methods in the Thread class are static.
Invoking one of the static methods performs the operation
‘on the currently running thread.
public static void | Causes the currently running thread
yield() to yield to any other threads of the
jority that are waiting to be
Starts the thread in a separate
path of execution, then invokes
the run() method on this Thread
object.
public static void | Causes the currently running thread
Wf this Thread object _was|| | sleep(long millisec) | to block for at least the specified
instantiated using a separate ‘number of milliseconds
Runnable target, the run() -
method is invoked on that Returns true if the current thread
Runnable object. holds the lock on the given Object.
Changes the name of the Thread
object. There is also a getName()
‘method for retrieving the name.
© scanned with OKEN ScannerExit from Thread B");
41-7 Thread Exceptions
7 Most call to sleepy ) method is enclosed within
caught. If
not compte Po” thread isnot catched, progr
© scanned with OKEN Scannersleeping thread cannot deal wi
ith the
) method because a sleeping thread cannot
ny Instructions. Even for suspend( ) method
thread method is called which is t
the appropriate exception handi
F throwing an
“supplied which catch the exce
let must be
Nn thrown by thread.
with example.
| What thread pronty 7 Wee defaut priory val
‘and methods to change them. (S-14, S17, 41
Explain thread priorty and method to get and set
priority values. AWENS, $184
Priority decides execution of time of thread means at
what time the thread is to be executed. Thread is
assigned a priority, which affects the order in which it
is scheduled for execution or running.
Java scheduler gives equal treatment to equal priority
threads. Hence, equal priority threads may shares the
Processor on a first-come-first serve basis.
Java assigns to each thread a priority that determines
how that thread should be treated with respect to
others. Thread priorities are used by the thread
scheduler to decide when each thread should be
allowed to run. Higher priority thread gets more CPU
time than lower priority threads. Threads of equal
Priority get equal access to CPU. The thread priority is
Used to decide when to switch
thread to the next, this is known
Following are the rules that determi
‘switch takes place :
from one running
as context switch.
line when a context
© scanned with OKEN Scanner‘Thread priorities are integers that specify the relative
Prec be assigned by using
System.out.printin("4Exit from Thread |
priority. (From 1 to 10),
getPriority( )
= This method is used to get the priority of thread. )
— The Thread dass defines following priority constants: | Jelass B extends Thread
[MIN_PRIORITY = 2 fi
NORM_PRIORITY = 6 public void rund)
MAx{PRIORITY = 10 (
_- System out printin("\tThread B Strated”),
‘By default intNumber is set to NORM_PRIORITY or 6.
for(int j=15;5<- 453i)
For a thread of lower priority to gain control, one of
‘the following must happen :
4. It stops running at the end of run() method.
2. Itismade to sleep using sleep () method.
3, tis told to wait using wait () method.
‘Whenever higher priority thread comes, the currently
running thread will be preempted by incoming thread.
‘And thus it forces the current running thread to move
‘tothe runnable state.
Thus, higher priority thread always preempted lower
- priority threads.
Following program shows the effect of assigning
| higher priority to threads. Here thread Ais started fis,
"the higher priority thread 8 preempts A and started
‘printing. immediately thread C of higher priority arrives
takes control over other two threads. Thus thread A is
© scanned with OKEN ScannerException Handling and Multithre
ae d bee
| public void rund)
iG
forlint HOi<3;i+4)
{
‘Thread cur-Thread.currentThread(;
cur.setPriority(Thread.MIN_PRIORITY);
d MAX_PRIORITY); int p=cur.getPriority();
B.setPriority(threadA..getPriority()+1); ‘System.out.printin("Thread Name :"
AX setPriorty(Thread MIN. PRIORITY); +Thread.currentThread ().getName());
"following program demonstrates the getPriorty() and
()methods :
‘this program two threads are created. Maximum
ty for the first thread "MyThread2” and ‘minimum
ty for the first thread "MyThread1" i.e. the after
the program, the first thread is executed only
nd the second thread "MyThread2" started to run
ft gets end or another thread of the equal
‘ready to run state.
© scanned with OKEN Scannerangi to. secess 00. 0, shared: (SsOuEMy
of the shared resource must be
‘nly one thread at atime. The synchronization
is used to achieve this.
For example : One thread trying to read records
file while another thread is still writing to the 7
In Java, this problem can be overcome by |
technique known as synchronization. The ke
synchronized is used.
When method is declared as synchronized,
creates a monitor (semaphore) and hands it over
thread that calls method for first time. A-monitor.
object that is used as @ mutually exclusive
mutex. Only one thread can own a monitor at a
time. When a thread acquires a lock, it is said to
entered the monitor. A long as the thread ho
monitor, no other thread can enter the
section of code. Monitor is similar to a key
These other threads are said to be waiting
monitor. f
aL TeuTy nena
S ete
© scanned with OKEN Scanner2 thread completes its work of using
ized method, it will hand over the monitor to.
thread to use the same resource.
_ Inter Thread Communication
ghen a two are more thread exists in an application
nd they are communicating each other by exchanging
mation, then it is called as inter thread
munication. Thread pooling is avoided by using
thread communication. Thread pooling is always
ented by a loop to check some conditions
. Appropriate action may be taken if
on is true. if one thread wants to communicate
other thread, it uses method notify () and
al)
ie
im
three methods are used for implementing
communication. These methods are
d as final in object, therefore they are
in all the classes. These three methods may
nly from synchronized situation.
yt causes the thread to wait
notify ().
For example, suppose
Exception Handling and.
the thread A must access
Method! before it can release Method2, but thread B
cannot release Method1 until it gets hold of Method2.
Because these are mutually exclusive conditions, @
deadlock occurs.
Deadlock is a difficult error to debug for two reasons :
In general it occurs only rarely, when two threads
time-slice in just the right away.
It may involve more than two threads and two
synchronized objects. (That is deadlock can occur
through a more convoluted sequence of events
than just described).
The code below illustrates deadlock :
\
© scanned with OKEN ScannerErrors are WIONgs OF Mistakes thay ¢
program go wrong. Errors may be logics
‘An exception is an abnormal condition that a
code sequence at run time. That is, exception
time error. a
4.2.1 Types of Errors
1.
.rrors are classified into two categories:
Compile time errors
Run time error
Compile time Errors
Java compilers detect all syntax error
these errors are known as comp
compiler displays errors, oF e
contains error, the compiler does NOt
So it is necessary to fix all the errors
‘compilation and execution of pro
© scanned with OKEN Scanner© scanned with OKEN Scanner“tava exception is nothing but an object which
‘the information of an exceptional condition
For pass it on. Exception can be generated by the
“run time system or by manually by the code.
zeptions generated by the Java are related to the
© scanned with OKEN Scanner‘Any exception that is generated o
ut of
‘must be specified as such by a "intole?
# Any code that must be executed by
efore
‘method returns is put in a finally block, :
Idea of Exception handling mechanism are
an exception and catching it. Fig. 4.2.1 shows
tion handling mechanism.
: Exception handling mechanism
‘try keyword is used for the block of codes that
‘an error condition and throws an exception.
420
The try block contains one or more statement, which
generates exception. If the one statement generates:
the exception, then the remaining statements are
skipped and execution jumps to the catch block 1-
The catch block can also contain one oF more
statements which are necessary to process the
exception. Every try statement must be followed by at
least one catch statement, otherwise compilation error
‘occurs. Catch statement works same as method
definition. The catch statement is passed a single
parameter, which is reference to the exception object
thrown by the try block. If the catch parameter
‘matches with the type of exception object, then the
‘exception is caught and statements in the catch block
will be executed. Otherwise, the exception is not
‘caught and the default exception handles will cause
the execution to terminate.
All exception types are subclasses of the built in class
Throwable. Thus, the Throwable is at the top of the
exception class hierarchy. Two classes are derived from
the Throwable - errors and exception.
1. The Exception is used for exceptional conditions
that the user program should catch. The
RuntimeException is a subclass of Exception,
exceptions of this type are automatically defined
for the program that user write such as division
by zero,
Error defines exceptions that are not expected to
be caught under normal circumstances by
program. Exceptions of type Error are used by the
Java Runtime system to indicate errors having to
do with the run-time
see environment, such as sag
Any exception that is not caught by the
__ubmately be processed by the defautt
‘Keyword is used for the block of code that
the exception “thrown” by the try block and
it. The catch block is added immediately after
© scanned with OKEN Scanner© scanned with OKEN Scanner4 method is generating an exception but cannot
it, then, it is responsibilty of the method to
activities to caller method to guard themselves
that exception. To do this includes a throws
Jn the method's declaration. A throw clause
the types of exceptions that can be generated
‘method. The exceptions that can be generated by
d that can be thrown must be declared in the
ause. If they are not then the compile time
will be generated. The general form of a method
4.2.4 Multiple Catch Statements
Catch block can have more than one statement as
Throwableinstance must be an object of type
wable or subclass of Throwable. Primitive types,
int or char as well as non - Throwable classes,
“as String and Object, cannot be used as
‘There are two ways to obtain a Throwable
parameter in a catch cluse, oF creating
© scanned with OKEN Scannerexception object will get executed and remaining.
statements willbe skipped.
“Java does not require any processing of the exception,
‘then add a catch statement with an empty block to
avoid program abortion lke catch ( Exception e );
= Gatch statement ends with semicolon; which does
‘nothing. This statement catches an exception and then
42.8 Using Finally Statement
Finally statement is used to handle an exception thatis
not caught by any of the previous catch
finally block can be used to handle any exception
generated within a try block. Finally creates a block of
code that will be executed after a try/catch block has
completed and before code following the try/cateh
block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the
finally block will execute even if no catch statement
matches the exception. The finally clause is optional.
Itcan be added immediately after the try block or after
the last catch block shown below :
© scanned with OKEN ScannerException Handling and Multi
‘a finally block is defined, it gives guaranteed to
regardless of whether or not is exception is
finally
{ z
System.out.printin("proC finally");
} y
public static void main(String argsf])
© scanned with OKEN Scannerthe standard java lang package defines several builtin
ee Most of bebe. erceptlons ore’ the NullpointerException
‘subclasses of the standard type known as Runtime
Exception.
‘as the javalang is implicitly available to all java | | 12, |NumberFormatException stringtoa
programs, the exceptions derived from Runtime numeric format
Exception are automatically and easily available to java tiene
‘progrem. 13, |SecurityException violate security
sf Runtime
— There are two types of exceptions of Runtim aoc
_ 3 ‘ outside the
—— 14, | stringindexOutofBounds course
{i Checked RuntimeException aie
Following table list Unchecked Runtime Exception : [an unsupportial
15, |UnsupportedOperationException | operation was
encountered.
Arithmetic. error,
such as divide-
by-zero.
fArray index
. ArrayindesOutOFBoundsException |A2Y, inden
Assignment to an
array element of| [Attempt to clone an|
oe neompatle! | | 2. |cloneNotsupportedéxception ee a
invalid cast. - : Cloneable interface.
legal argument
used to invoke a
method.
ywing table list Checked RuntimeException
Class not found.
1. |ClassNotFoundException
MegalAccessException — oa
lenied. d
legal monitor i a |
ae | nstantiationException object of an abstract
class or interface
‘One thread has
interrupted
another thread.
© scanned with OKEN Scannerhe Help of chained exception it may be easier to
y that when one exception causes another
‘two constructor of Throwable class supports
jexception are listed below :
Throwable (Throwable cause) : The parameter
‘cause specifies the actual cause of exception
‘Throwable (String str, Throwable cause): The
| String str specifies exception description and
‘cause specifies the actual cause of exception.
_ Two methods of Throwable class that supports the
“chained exception :
{9 Throwable getCause/ ) : This method returns the
actual cause of the currently generated
‘exception.
Wo Throwable initCause( ) : This method sets the
fundamental exception with invoking exception.
|The program generates ArithmaticException which in
‘tum generates NumberFormatException.
: > 4.2.8 Throwing Our Own Exception
‘Our own exception can be thrown by using the
© scanned with OKEN Scannerprograms. Programmer can
rriguse this technique for hiding errors rather than
Jebugging the code. Exception handling mechanism is
rfectively used to locate the type and place of errors,
‘Once the errors are identified try to find out why there
or occurs before covering them up with exception
errors from rest of the
~ System out printin("Smaller number”);
i
Iclass Userex
Hf
© scanned with OKEN Scanner‘block within another try block is known as
st . Sometimes there may be a possibility
‘exceptions in same block of code, ie. a
ck code may cause one exception and another
‘block or entire block itself may cause another
‘in such situation, we need to use nested try
handle the exceptions.
© scanned with OKEN ScannerJn above program, the nested try statement is
‘available. The outer try statement is associated with
the catch block which is used to handle the
i ArithmeticException if it occurs in the outer try block.
i {Also the outer block contain the array related code that
$ ‘code is written into inner try block and that inner try
| _ Block is associated with the catch block which is used
tohandle the ArrayindexOutOfBoundException.
The outer try block contains the code of integer
division. Here, 50 is divided by the value of b and b
‘contains 10 hence, in this case no exception is occurred
and the flow of program will continue. Then in try block
the integer array of size 5 is created. And we try to
assign the value to the array index which is not
available. Hence inthis case the
ArrayindexOutOfBoundException is occurred, This
‘exception is handled by the catch block associated by
‘inner try block.
= But. if the value of b is set to 0 then the
ArithmeticException is occurred in the outer block only
___ by disturbing the flow of the program execution and
_ control transfer to the catch block associated to the
‘outer try block, where the Arithmetic exception is
‘handled. n this case inner try block does not execute.
‘catch (IOException ¢)
{
System.out.print("I did not get your
‘name.");
© scanned with OKEN Scanner‘name3=("+abe.charAt(a))..
: ‘toUpperCase());
" name3=name3+(""+abe.charAt(a)),
toLowerCase())
public static void main(String args(])
i : 4
int a=10,b=5,0°5;
* int result;
try
{
result=a/(b-c);
3
catch(Exception ¢)
{
‘Error !!");
}
— resulteal(be);
Syren” Rea: * seem,
© scanned with OKEN Scanner
‘System. out, printin(” Diels By 739 Zeiflali)> afi)
int temp = aly];
alj) = a1:
afj+1] = temp;
}
System out, penta tascnding Oder of 4
numbers:
for(int i =0;i<5;i+-+)
{
‘System.out printn("\t "+a[i});
eS
}
poe
|class Descending extends Thread
{
© scanned with OKEN Scannernumbers in Ascending Order is started")
new Ascending0 start); 3
tem ‘out printin("n\tSecond thread printing ‘ante hi in Descending Order is started");
ers in Descending Order is started"); new Descending().start();
‘Write a program to create two threads so
print ascending number 1 to 10 where as
Eres
© scanned with OKEN Scanner‘System out printin("Enter the Name
name=br.readLine();
‘System.out printin("Enter age:");
iffage <0)
© scanned with OKEN Scanner[public static void main(String argsED)
el, 4 a
‘numbers from 1 10 10
‘new onetoten().start();
4.3.9 Write a program to create two threads so System out printin("ntSecond thread
{tread wil print 1 to 10 numbers whereas other vl print
new eleventotwenty() start)
i
Program 4.3.10 :Write a program to create a thread to print
zi all even numbers from 1 to'50 with a delay of 100 after each
cout printin("\n\tThread 1 (1 to 10)::"); |} | number.
10;i++)
© scanned with OKEN Scannercatch(Exception €){}
}
catch(IOException i)
{
System.out.printin(i);
Program 4.3.11 : Write a program to input a string and print
‘each character from that separately on screen with a delay
of 100ms after each character. class testDelay
if
public static void main(String argsf])
{
© scanned with OKEN Scannersword"); BufferedReader(new
ios InputStreamReader(System.in));
‘String usemame=br.readLine();
mout.printin(e.getMessage()); String password=br.readLine();
atic void main(String args{})
p El = new userExp0;
© scanned with OKEN ScannerProgram 4.3.15 : Write 2
‘exception as ‘invalid Age’,
import java.i ’
lclass MyException extends Exception
{
MyEixception ( String Message )
{
super ( Message ) ;
}
jclass UL
{
String name;
int age;
public void input()
{
© scanned with OKEN Scanner© scanned with OKEN Scanner