Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Java Unit IV

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java Unit IV

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

B.

SC-III Year III-Semester OOP using JAVA

Unit-IV

MultiThreaded
Programming

Dividing a program (process) into two or more


subprograms (processes),and implementing
them at the same time in parallel is known as
MultiThreading.

A thread is similar to a program that has a single


flow of control. It has a beginning, a body, and
an end, and executes commands sequentially.

The following figure shows a Single-Threaded


program:
The above figure shows a [Java] program with
four threads, one main and three others. The
main thread is the main method, which is
designed to create and start the other three
threads, namely A, B and C. Once initiated by
the main thread, these three threads run
concurrently and share the resources jointly.

The ability of a language to support


multithreads is known as concurrency. The
threads in Java are subprograms of a main
application program. They can share the same
memory space. So that they are known as
lightweight threads or lightweight processes.
Java supports multithreading. Java enables us
to use multiple flows of control in developing Multithreading is useful in a number of ways. It
programs. enables programmers to do multiple things at
one time. They can divide a long program into
Each flow of control is known as a thread. threads and execute them in parallel.
These threads run in parallel to others.
Java Threads
A program that contains multiple flows of
control is known as multithreaded program. Java threads can be created simply as like the
objects. Threads are implemented in the form
The following figure shows a Multi-Threaded of objects that contain the run() method. The
program: run( ) method is the heart and soul of any
thread. It makes up the entire body of a thread
and implements the threads behaviour.

ANDHRA LOYOLA COLLEGE Page |1


B.SC-III Year III-Semester OOP using JAVA

...............
A typical run() method will have the following }
format:
Now we have a new type of thread MyThread.
public void run( )
{ 2. Implementing the run() Method:
..........
.......... The run( ) method has been inherited by the
// (statements for implementing thread) class MyThread. We have to override this
.......... method in order to implement the code to be
} executed by our thread.

The run() method should be invoked with the The basic implementation of run() will look
help of a thread method called start () by an like this:
object of the concerned thread.
public void run()
Creating Threads {
................
A new thread can be created in two ways. ................// Thread code here
1. By creating (extending) a thread class: ................
Define a class that extends Thread class and }
override its run( ) method with the code
required by the thread. When we start the new thread, Java calls the
thread’s run( ) method. So that the run() method
2. By converting a class to a thread: can perform all its given tasks.
Define a class that implements Runnable
interface. The Runnable interface has only one 3. Starting New Thread:
method, run( ), that is to be defined in the To start a new thread, first we need to create an
method with the code to be executed by the object of thread class and then we need to call
thread. it using the start () method.
For example:
Extending the Thread class
MyThread mt = new MyThread( );
We can make our class to be runnable as thread mt.start( ); // invokes run() method
by extending the class java.lang.Thread. This
gives us access to all the thread methods Example Program:
directly.
class A extends Thread
It includes the following steps: {
1. Declare the class as extending the Thread public void run( )
class. {
2. Implement the run( ) method. for (int i = 1; i < = 5; i + +)
3. Create a thread object and call the start( ) {
method. System.out.println(“\ t From Thread
A : i = ” + i);
1. Declaring the Class: }
The Thread class can be extended as follows: System. out. println(“ Exit from A “);
class MyThread extends Thread }
{ }
...............
...............

ANDHRA LOYOLA COLLEGE Page |2


B.SC-III Year III-Semester OOP using JAVA

class B extends Thread Blocking a Thread


{
public void run( ) A thread can also be temporarily suspended or
{ blocked by using either of the following thread
for( int j = 1; j < = 5; j + +) methods:
{
System.out.println(“\ tFrom sleep( ): The sleep() method blocks a thread for
Thread B :j = ” + j); a specified time. The thread will return to the
} runnable state when the specified time is
System. out. println(“ Exit from B “); elapsed.
}
} suspend( ): The suspend() method blocks a
thread until further orders. The resume( )
class C extends Thread method can be used to invoke a suspendded
{ thread.
public void run( )
{ wait( ) : The wait() method blocks a thread until
for( int k = 1; k < = 5; k + +) certain condition occurs. The notify() method
{ can be used to invoke a waiting thread
System.out.println(“\ tFrom Thread
C : k = ” + k); LIFE CYCLE OF A THREAD
}
System. out. println(“ Exit from C ”); A Thread may enter into different states during
} its life cycle. They include:
}
1. Newborn state
class ThreadTest 2. Runnable state
{ 3. Running state
public static void main( String args[ ]) 4. Blocked state
{ 5. Dead state
new A( ). start( ); The following figure shows the Thread Life
new B( ). start( ); Cycle:
new C( ). start( );
}
}

Stopping a Thread

The stop() method will stop a thread from


running further. The stop() method causes the
premature death of a thread .

For Example: aThread.stop( );

This statement causes the thread to move to the


dead state.
A thread will also move to the dead state
automatically when it reaches the end of its
method.
Figure: Thread Life Cycle

ANDHRA LOYOLA COLLEGE Page |3


B.SC-III Year III-Semester OOP using JAVA

Newborn State:
When we create a thread object, the thread is 1. It has been suspended: A running thread
born and is said to be in newborn state. At this can be suspended using suspend( )
state, we can do only one of the following method. A suspended thread can be revived
things with it: by using the resume( ) method.
• Schedule it for running using start( )
method.
• Kill it using stop( ) method.

2. It has been made to sleep: We can put a


thread to sleep for a specified time period
using the method sleep( time). The thread
re-enters the runnable state as soon as this
time period is elapsed.

Figure: Scheduling a newborn thread


3. It has been told to wait: A running thread
If we attempt to use any other method at this can be told to wait using the wait( ) method.
stage, an exception will be thrown. The thread can be scheduled to run again using
the notify( ) method.
Runnable State:
The runnable state means that the thread is
ready for execution and is waiting for the
availability of the processor.
If all the waiting threads have equal priority,
then they are given time slots for execution in
first-come, first-serve manner. This process of Blocked State:
assigning time to threads is known as time- A thread is said to be blocked when it is
slicing. prevented from entering into the
runnable/ruunning states. This happens when
We can giveup(relinquish) one threads control the thread is suspended, sleeping, or waiting. A
to another thread by using the yield() method. blocked thread can be possible to run again.

Dead State:
A running thread ends its life when it has
completed executing its run( ) method. It is a
natural death. We can also kill a thread by
sending the stop() message to it at any state.
This causes a premature death to it. A thread
Running State: can be killed from new born state, or running
Running means that the processor has given its state, or even in blocked states.
time to the thread for its execution. A running
thread may relinquish its control in one of the
following situations:

ANDHRA LOYOLA COLLEGE Page |4


B.SC-III Year III-Semester OOP using JAVA

USING THREAD METHODS: System.out.println(“\ tFrom Thread B:j= +j);


Thread class methods can be used to control the if( j = = 3)
behaviour of a thread. The following are some stop( );
important thread methods: }
System.out.println(“ Exit from B “);
Thread Method Description }
start() Starts a thread by calling }
its run method
getName() Gives a thread’s name class C extends Thread
getPriority Gives a thread’s priority {
isAlive() Determine if a thread is public void run( )
still running {
join() Wait or a thread to for (int k = 1; k < = 5; k + +)
terminate {
sleep() Blocks a thread for a System.out println(“\ tFrom Thread
specified time C:k=”+k);
suspend() Blocks a thread until if( k = = 1)
further orders try
{
wait() Blocks a thread until
sleep( 1000);
further orders
}
resume() Revives a blocked thread
catch (Exception e) { }
notify() Schedules a Waiting
}
thread for running again
System. out. println( “Exit from C ”);
yield() Gives up a threads control
}
to another thread
}
Note: stop(), suspend(), resume() methods class ThreadMethods
are deprecated {
public static void main( String args[ ])
{
Use of yield( ), stop( ), and sleep( ) methods; A threadA = new A( );
class A extends Thread B threadB = new B( );
{ C threadC = new C( );
public void run( ) System. out.println(“ Start thread A”);
{ threadA.start( );
for( int i = 1; i < = 5; i + +) System.out.println(“ Start thread B”);
{ threadB.start( );
if( i = = 1) System.out.println(“ Start thread C”);
yield( ); threadC.start( );
System.out.println(“\ tFrom Thread A: i System.out.println(“ End of main thread”);
=”+i); }
} }
System.out.println(“ exit from A ” );
}
}

class B extends Thread


{
public void run( )
{
for( int i = 1; i < = 5; j + +)
{

ANDHRA LOYOLA COLLEGE Page |5


B.SC-III Year III-Semester OOP using JAVA

THREAD EXCEPTIONS
The intNumber is an integer value to which the
Java run system will throw thread’s priority is set.
IllegalThreadStateException whenever we
attempt to invoke a method that a thread cannot The Thread class defines several priority
handle in the given state. constants:
MIN_PRIORITY = 1
For example, a sleeping thread cannot deal with NORM PRIORITY = 5 (Default Setting)
the resume( ) method. Because a sleeping MAX_PRIORITY = 10
thread cannot receive any instructions.
The intNumber may assume one of these
A blocked thread cannot deal with the constants or any value between 1 and 10.
suspend() method.
Most user-level processes should use
Whenever we call a thread method that is likely NORM_PRIORITY, plus or minus 1.
to throw an exception, we have to supply an
appropriate exception handler to catch it. Background tasks such as network I/ O and
screen repainting should use a value very near
The catch statement may take one of the to the lower limit.
following forms:
A highest priority thread always preempts any
catch (ThreadDeath e) lower priority threads.
{
................ Example:
................ // Killed thread
} class A extends Thread
catch (InterruptedException e) {
{ ................. public void run( )
................. // Cannot handle it in the current {
state System.out.println(“ threadA started”);
} for( int i = 1; i < = 5; i + +)
catch (Illegal ArgumentException e) {
{ ............... ............... // Illegal method System. out. println(“\t From
argument Thread A : i = ” + i);
} }
catch (Exception e) System. out. println(“ Exit from A ”);
{ ................ }
................ // Any other }
}
class B extends Thread
Thread Priority {
In Java, each thread is assigned a priority. It public void run( )
affects the order in which it is scheduled for {
running. The threads of the same priority can System.out.println(“ threadB started”);
share the processor on a first-come, first-serve for( int j = 1; j < = 5; j + +)
basis. {
Java permits us to set the priority of a thread System. out. println(“\tFrom
using the setPriority( ) method. It has the Thread B : j = ” + j );
following format: }
System. out. println(“ Exit from B ”);
ThreadName.setPriority( intNumber); }

ANDHRA LOYOLA COLLEGE Page |6


B.SC-III Year III-Semester OOP using JAVA

} In case of Java, the keyword synchronized


helps to solve such problems by keeping a
class C extends Thread watch on such locations.
{ Example:
public void run( ) synchronized void update( )
{ {
System.out.println(“threadC started”); ................
for( int k = 1; k < = 4; k + +) ................ // code here is
{ synchronized
System. out. println(“\ tFrom Thread C : k ................
= ” + k); }
}
System.out.println(“ Exit from C ”); When we declare a method synchronized, Java
} creates a “monitor” and hands it over to the
} thread that calls the method first time. As long
class ThreadPriority as the thread holds the monitor, no other thread
{ can enter the synchronized section of code. A
public static void main( String args[ ]) monitor is like a key and the thread that holds
{ the key can only open the lock.
A threadA = new A( );
B threadB = new B( ); The following program illustrates the
C threadC = new C( ); importance of synchronization in a
threadC.setPriority( multithreaded program.
Thread.MAX_PRIORITY);
threadB.setPriority( threadA.getPriority( )+ 1); class Pyramid
threadA.setPrioirty( {
Thread.MIN_PRIORITY); synchronized void draw_pyramid( char ch)
System. out.println(“ Start thread A”); {
threadA.start( ); for( int i = 0; i < 10; i + = 2)
System.out.println(“ Start thread B”); {
threadB.start( ); for( int k = 10-i; k > 0; k-= 2)
System.out.println(“ Start thread C”); {
threadC.start( ); System.out.print(“ “);
System.out.println(“ End of main thread”); }
} for( int j = 0; j < = i; j + +)
} {
System.out.print( ch);
SYNCHRONIZATION }
System.out.println();
Sometimes when the threads try to use data and }
methods outside themselves. On such }
occasions, they may compete for the same }
resources and may lead to serious problems.
class A extends Thread
For example, one thread may try to read a {
record from a file while another is still writing Pyramid p;
to the same file. Depending on the situation, we A( Pyramid p)
may get strange results. Java enables us to {
overcome this problem using a technique this.p = p;
known as synchronization. }
public void run( )

ANDHRA LOYOLA COLLEGE Page |7


B.SC-III Year III-Semester OOP using JAVA

{ public void run( )// Step 2


p.draw_pyramid(‘*’); {
} for( int i = 1; i < = 10; i + +)
} {
System.out.println(“\tThreadX ” + i);
class B extends Thread }
{ System. out.println(“ End of ThreadX”);
Pyramid p; }
B( Pyramid p) }
{ class RunnableTest
this.p = p; {
} public static void main( String args[ ])
public void run( ) {
{ X runnable = new X( );
p.draw_pyramid(‘#’); Thread threadX = new Thread( runnable);// 3
} threadX. start( ) ;// Step 4
} System.out.println(“ End of main
class SynchTest Thread”);
{ }
public static void main( String args[ ]) }
{ *****
Pyramid pobj = new Pyramid();
A threadA = new A( pobj);
B threadB = new B( pobj); Exception Handling
threadA.start(); Errors are the wrongs that can make a program
threadB.start(); go wrong. In computer terminology errors may
} be referred to as bugs.
} It is common to make mistakes while
IMPLEMENTING THE ‘RUNNABLE’ developing as well as typing a program. An
INTERFACE error may produce an incorrect output or may
terminate the execution of the program abruptly
In Java, a thread can also be created by or even may cause the system to crash. It is
implementing the Runnable interface. The therefore important to detect and manage the
Runnable interface declares the run( ) method possible errors.
that is required for implementing threads in our Types of Errors
programs. Errors may be broadly classified into two
We must follow the following given stpes to categories:
implement the Runnable interface: 1. Compile-time errors
1. Declare the class as implementing the 2. Run-time errors
Runnable interface.
2. Implement the run( ) method. Compile-Time Errors:
3. Create a thread object of the “runnable” All syntax errors that are detected and
class displayed by the Java compiler are known as
4. Call the thread’s start( ) method to run the compile-time errors.
thread. ▪ Whenever the compiler displays an
error, it will not create the .class file.
The following program illustrates the ▪ It is easy for the programmer to correct
implementation of Runnable interface: these errors because Java compiler tells
using Runnable interface" us where the error has occurred.
class X implements Runnable// Step 1
{

ANDHRA LOYOLA COLLEGE Page |8


B.SC-III Year III-Semester OOP using JAVA

The following Java Program causes a compile- ▪ Attempting to use a negative size for an
time error: array Converting invalid string to a
Class CompileTimeError1 number
{ ▪ Accessing a character that is out of
public static void main(String args[]) bounds of a string
{ Example: The following code generates a
System.out.println(“ Hello Java!”) runtime error.
// The above line Missing ; ( Semi Colon) Class RunTimeTimeError1
} {
} public static void main(String args[])
{
▪ When executing this program produces int a= 10;
the following error message: int b = 5;
int c = 5;
CompileTimeError1.java :6: ‘;’ expected int x = a/(b-c); //division by zero error
System.out.println(“ Hello Java!”) System.out.println(“x =”+x);
^ int y = a/(b+c);
1 Error. System.out.println(“y =”+y);
Most of the compile-time errors are due to }
typing mistakes. }
It displays the following message and stops
The most common compile-time errors are:
execution
▪ Missing semicolons
Java.lang.ArithmeticException: / by zero
▪ Missing brackets in classes and
Exceptions:
methods
Exception: An Exception is a condition caused
▪ Misspelling of identifiers and keywords
by a runtime error in a program. It is an
▪ Missing double quotes in strings
abnormal event that arises during the execution
▪ Use of undeclared variables
of the program and terminates the normal flow
▪ Use of Incompatible types in
of the program. Java has a built-in mechanism
assignments / initialization
for handling runtime errors, known as
▪ Bad references to objects
exception handling.
▪ Use of = in place of = = operator
Exception Handling: Handling runtime errors
Run-Time Errors:
is known as exception handling. When an
Sometimes, a program may compile
abnormal condition occurs within a method
successfully and it also creates a .class file but
then JAVA throws an exception in the form of
it may not run properly.
Exception Object. If the exception object is not
▪ It may produce wrong result due to
caught and handled properly, the interpreter
wrong logic or may terminate due to
will display an error message and it will
errors such as ‘divide by zero’.
terminate the program. If we want the program
to continue with the execution of the remaining
Most common run-time errors are:
code, then we should try to catch the exception.
Advantages of Exception-handling in Java:
▪ Dividing an integer by zero
▪ It ensures safer termination of a
▪ Accessing an element that is out of the
program.
bounds of an array
▪ It demands proper input entry or proper
▪ Trying to store an incompatible value
handling of a program.
into an array
▪ User has a chance to correct the
▪ Passing an invalid parameter for a
accidental mistakes while running a
method
program.
▪ Trying to illegally change the state of a
thread

ANDHRA LOYOLA COLLEGE Page |9


B.SC-III Year III-Semester OOP using JAVA

▪ The program becomes robust and more • InterruptedException


user-friendly.
▪ With this mechanism the working code An Unchecked exception can always deal with
and the error-handling code can be programmatic run time errors. These
disintegrated. exceptions are also called Runtime exceptions.
▪ It allows different handling code-blocks These are usually caused by the errors such as
for different types of errors. ArithmeticException,
NumberFormatException,
Types of exceptions: ArrayIndexOutOfBounds Exception.
In JAVA we have two types of exceptions. The following are the list of unchecked
Those are: exceptions:
1. Pre-defined Exceptions ▪ IndexOutOfBoundsException
2. User-defined or custom defined ArrayIndexOutOfBoundsException
exceptions. ▪ ClassCastException
Predefined exceptions: ▪ ArithmeticException
Predefined exceptions are those which are ▪ NullPointerException
developed by SUN micro systems. These are a ▪ IllegalStateException
part of JDK. Predefined exceptions can deal ▪ SecurityException
with universal problems
Predefined exceptions are divided into two How an EXCEPTION OCCURS in JRE
types. Those are: 1. Whenever we pass irrelevant input to a
▪ Asynchronous Exceptions JAVA program, JVM cannot process the
▪ Synchronous exceptions. irrelevant input.
Asynchronous exceptions can deal with 2. JVM can contact to JRE for getting an
hardware problems. These exceptions are a part appropriate exception class.
of the java.lang.Error class. This becomes the 3. JRE contacts to java.lang.Throwable for
super class for all asynchronous exceptions. finding what type of exception it is.
Synchronous exceptions can deal with 4. java.lang.Throwable decides what type of
programmatic errors. These exceptions are a exception it is and pass the message to JRE.
part of the java.lang.Exception class. This 5. JRE pass the type of exception to JAVA API.
becomes the super class for all synchronous 6. From the JAVA API either java.lang.Error
exceptions. class
Synchronous exceptions are divided into two Or
types. Those are: java.lang.Exception class will found an
▪ Checked exceptions. appropriate sub class exception.
▪ Unchecked exceptions. 7. Either java.lang.Error class or
A checked exception can always deal with java.lang.Exception class gives an appropriate
compile time errors. Checked exceptions are exception class to JRE.
required to be caught. For example if we call 8. JRE will give an appropriate exception class
the readLine() method with a BufferedReader to JVM.
object then the IOException may occur. For 9. JVM will create an object of appropriate
this, our method should have code to handle the exception class which is obtained from JRE
IOException. and it generates system error message.
The following are the list of checked 10. In order to make the program very strong
exceptions. (robust), JAVA programmer must convert
• NoSuchFieldException the system error messages into user friendly
• InstantiationException messages by using the concept of exceptional
• IllegalAccessException handling. Because User friendly messages are
• ClassNotFoundException better understood by normal users hence our
• NoSuchMethodException program is robust.
• CloneNotSupportedException

ANDHRA LOYOLA COLLEGE P a g e | 10


B.SC-III Year III-Semester OOP using JAVA

Exception Handling
Exception Handling: Handling runtime errors is
known as exception handling.
When an abnormal condition occurs within a
method then
• JAVA throws an exception in the form
of Exception Object.
• If the exception object is not caught and
handled properly, the interpreter will
display an error message and it will
terminate the program.
• If we want the program to continue with
the execution of the remaining code,
then we should try to catch the
exception. It has the following syntax:
The purpose of exception handling is to detect try
and report an "exceptional condition", So that {
appropriate action can be taken. Statements that may cause an exception
The mechanism performs the following tasks: }
1. Find the problem. catch(Exception-Type1 a)
2. Inform that an error has occurred (Throw {
the exception) Statements to handle exception ‘a’
3. Receive the error information (Catch the }
exception) catch(Exception-Type2 b)
4. Take corrective actions (Handle the {
exception) Statements to handle exception ‘b’
The error handling code basically consists of }
two segments: ….
• one to detect errors and to throw ….
exceptions and finally
• The other to catch exceptions and to {
take appropriate actions. Statements;
}
Exception handling mechanism includes the
key words: try, catch, throw, throws and try-block: “try” block contains the code that
finally. may cause a runtime error. It throws
Exception object. A try block must be followed
The following figure shows the exception by at least one catch block or a finally block.
Handling mechanism:
catch-block: “catch” block contains the code
to handle runtime errors i.e. when run time
error occurs then, the control comes to “catch”
block.
• We can write multiple “catch” blocks to
handle different errors. We must
mention the type of exception in a
“catch” block.

finally-block: The finally block is always


executed, it is recommended for actions like

ANDHRA LOYOLA COLLEGE P a g e | 11


B.SC-III Year III-Semester OOP using JAVA

closing file streams and releasing system try


resources. {
• If no exception occurs during the System.out.println(“Division=”+ (a/b));
running of the try-block, all the catch- }
blocks are skipped, and finally-block catch(ArithmeticException e)
will be executed after the try-block. {
System.out.println("Please check
the Denominator”);
JAVA-System Defined Exceptions System.out.println(e);
All exceptions are system defined classes. }
They are subclasses of either ‘Exception’ or }
‘RuntimeException’ class. }
The following are some common system-
defined exceptions: The above program produces the following
1. ArithmeticException: Caused by math output.
errors such as division by zero. Output 1: (No Exception)
2. ArraylndexOutOfBoundsException: D:\java>java Test 6 2
Caused by bad array indexes. Division =3
3. ArrayStoreException: Caused when a Output 2: (With Exception)
program tries to store the wrong type of data in D:\java>java Test 6 0
an array. Please check the Denominator
4. FileNotFoundException: Caused by an Program to catch
attempt to access a nonexistent file. ArrayIndex OutOfBounds Exception
5. lOException : Caused by general I/O
failures. It is raised in a program when we use invalid
6. NullPointerException: Caused by index i.e. an index value i.e. greater than or
referencing a null object. equal to its size is used.
7. NumberFormatException: Caused when a
conversion between strings and number fails. class Test
8. OutOfMemory Exception: Caused when {
there's not enough memory to allocate a new public static void main(String as[])
object. {
int a[]={10,20,30,40};
9. SecurityException: Caused when an applet try
tries to perform an action not allowed by the {
browser's security setting. for(int i=0;i<10;i++)
System.out.print("\t"+a[i]);
10. StackOverFlowExceptlon: Caused when
}
the system runs out of stack space.
catch(ArrayIndexOutOfBoundsException
11. StringlndexOutOfBoundsExceptlon: ae)
Caused when a program attempts to access a {
nonexistent character position in a string. System.out.println("Array has
"+a.length+" elements only");
Example: The following program }
demonstrates exception handling. }
class Test }
{ The above program produces the following
public static void main(String as[]) output.
{ 10 20 30 40
int a=Integer.parseInt(as[0]); Array has 4 elements only
int b=Integer.parseInt(as[1]);

ANDHRA LOYOLA COLLEGE P a g e | 12


B.SC-III Year III-Semester OOP using JAVA

finally block
Multiple catch blocks
Several types of exceptions may arise when The finally block is always executed, regardless
executing the program. They can be handled by of whether or not an exception is thrown.
using multiple catch blocks for the same try
block. It is recommended for actions like closing file
In such cases, when an exception occurs the run streams and releasing system resources.
time system will try to find match for the • If no exception occurs during the
exception. When a match is found then the running of the try-block, all the catch-
corresponding catch block will be executed. blocks are skipped, and finally-block
class Test will be executed after the try-block.
{
public static void main(String args[]) • The finally block may be added after the
{ catch block, or after the last catch block.
try
{
int x=Integer.parseInt(args[0]); finally block after the catch block:
int y=Integer.parseInt(args[1]); try
System.out.print("Division="+ (x/y)); {
} Statements that may generate
catch(ArithmeticException ae) the exception
{ }
System.out.println("Denominator was finally
zero"); {
} Statements to be executed before
catch(NumberFormatException ne) exiting exception handler
{ }
System.out.println("Please supply Here, it moves to finally block but does not
numbers"); handle the exception.
}
catch(ArrayIndexOutOfBoundsException ie) finally block after the last catch block:
{ try
System.out.println("Please supply two {
arguments "); Statements that generate the exception
} }
} catch(Exception-Type1 a)
} {
Statements to process the exception ‘a’
The above program produces the following }
output in different runs. …. // other catch blocks
c:\jdk1.5\bin>java Test 8 0 ….
Denominator was zero finally
c:\jdk1.5\bin>java Test xx yy {
Please supply numbers Statements to be executed before exiting
c:\jdk1.5\bin>java Test 5 exception handler
Please supply two arguments }

Here, it handles the exception and moves to


finally block.

ANDHRA LOYOLA COLLEGE P a g e | 13


B.SC-III Year III-Semester OOP using JAVA

Example program: • A distributed application (Applet) is


class Test one which runs in the context of
{ browser or World Wide Web. It does
public static void main(String as[]) not contain main methods and
{ System.out.println statements.
int a=Integer.parseInt(as[0]);
int b=Integer.parseInt(as[1]);
try APPLETS
{ Applets are small java programs that are mainly
System.out.println(“Division=”+ (a/b)); used in Internet computing.
} • Applets are compiled using javac
catch(ArithmeticException e) compiler and can run inside a web
{ browser or in applet viewer.
System.out.println("Please check the • Applets can be useful to perform
Denominator”); arithmetic operations, display graphics,
} play sounds, accept user input, create
finally animation, etc.
{ • When applet arrives on the client, it has
System.out.println("Inside finally limited access to resources, so that it can
block”); perform complex computations without
} any viruses or security problems.
}
} Types of Applets
The above program produces the following
output. Applets can be of two types:
Output 1: (No Exception) 1. Local Applet
D:\java>java Test 6 2 2. Remote Applet
Division =3
Inside finally block Local Applets: A local applet is the one that is
Output 2: (With Exception) stored on our own computer system. It can be
D:\java>java Test 6 0 loaded from the local directory. Internet
Please check the Denominator connection is not required to use a local applet.
Inside finally block.

Applet Programming

In JAVA we can write two types of


applications. They are:
1. Standalone applications
2. Distributed applications.

• A standalone application is one which


runs in the context of local disk. Every
standalone application runs from
command prompt and it contains main Remote Applets: A remote applet is the one
method along with System.out.println which is developed by someone else and is
statements. stored on a remote computer. A remote applet
can be downloaded onto our computer via the
Internet. To download a remote applet, we must

ANDHRA LOYOLA COLLEGE P a g e | 14


B.SC-III Year III-Semester OOP using JAVA

know the applet's URL. It must be specified in Building Applet Code/Procedure to create
the CODEBASE attribute of HTML. and execute an applet
The following are the steps to create and
execute an applet:
1. Building an applet code (.Java file) by
importing Applet class.
2. Creating an executable applet (.class file)
3. Designing a Web page using HTML tags
4. Preparing the <applet> tag
5. Adding <applet> tag to the html document.
6. Running the applet.

Step 1: Import applet package and awt


package:
How applets differ from other • To create an applet, our program must
applications? import the Applet class. This class is
Applets have the following restrictions: found in the java.applet package. The
Applet class contains code for applet
• Applets do not use the main () method.
programming.
When an applet is loaded, it
automatically calls certain methods of • We also need to import the
Applet class to start and execute the java.awtpackage. "awt” stands for
applet code. “Abstract Window Toolkit”. The
java.awt package includes classes such
• An applet cannot be run independently.
as Graphics, Font, Color, etc.
They can be run from inside a Web page
using HTML tags.
Step 2: Extend the Applet class:
• Applets cannot read from or write to the
We need to define a class that inherits from the
files in the local computer.
class ‘Applet’. It contains the methods to paint
• Applets cannot communicate with other the screen. The inherited class must be declared
servers on the network. public.
• Applets cannot run any program from
the local computer. Step 3: Override the paint method to draw
• Applets cannot support native methods. text or graphics:
• Applets are meant for web-based The paint method needs the Graphics object as
applications. its parameter.
• All applets are subclasses of “Applet” For example:
class.
When do we use Applets? public void paint(Graphics g)
The following are the situations when we might {
need to use applets. ……….…
• When we need something dynamic }
content in a Web page.
• When we require some "flash" outputs The Graphics class object holds information
to produce sounds, animations or some about painting. By using this we can invoke
special effects. methods like drawLine(), drawCircle() and etc.
• When we want to create a program and
make it available on the Internet for us
by others on their computers.

ANDHRA LOYOLA COLLEGE P a g e | 15


B.SC-III Year III-Semester OOP using JAVA

Example: Output:

MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to
Applets”,10,50); Applet tag
} Applets are embedded in HTML documents
} with the <APPLET> tag. The Applet tag
Step 4: Compiling the Program: provides the name of the applet to be loaded and
• After writing the program, we can also tells the browser how much space it
compile it using the command "javac requires. The <applet....> tag included in the
MyApplet.java". body section of HTML file.
• This command will compile our code It has the following syntax:
and can create MyApplet.class file. <APPLET [codebase=codebaseURL]
Step 5: Adding applet to HTML document: code=”Applet file”
• To run the applet we need to create the [ALT=”alternative text]
HTML document. [name=AppletInstanceName]
• The BODY section of the HTML Width=pixels height= pixels
document allows APPLET tag. [align= alignment]
>
MyApplet.html: [<param name=”Attributename” value
=”Attribute value”]
<html> [<param name=”Attributename” value
<body> =”Attribute value”]
<applet code ="MyApplet.class" width=800 ........
height=500> [HTML displayed in the absence of java]
</applet> </APPLET>
</body>
</html> CODEBASE: (codebaseURL): This attribute
specifies the URL of the applet.
Step 6: Running an applet: CODE: (appletFile): This attribute gives the
An applet can be run in two ways name of the file that contains the applet's class
file.
1. Using appletviewer: To run the ALT: (alternateText): This attribute specifies
appletviewer, type appletviewer any text that should be displayed if the browser
filename.html can't run Java applets.
NAME: (appletInstanceName): This attribute
2. Using web browser: Open the web specifies a name for the applet instance, which
browser, type in the full address of makes it possible for applets on the same page
html file. to find and communicate with each other.
WIDTH, HEIGHT (in pixels): These
attributes give the initial width and height (in
pixels) of the applet display area.
ALIGN (alignment): This attribute specifies
the alignment of the applet. The possible values

ANDHRA LOYOLA COLLEGE P a g e | 16


B.SC-III Year III-Semester OOP using JAVA

are: left, right, top, texttop, middle, absmiddle, Running State:


bottom, absbottom. After initialization, this state will automatically
VSPACE, HSPACE (in pixels): These occur by invoking the start() method of applet.
attributes specify the number of pixels above The start() method may be called multiple times
and below the applet (VSPACE) and on each when the Applet needs to be started or restarted.
side of the applet (HSPACE). If the user leaves the applet and returns back,
Param Name and Value: The PARAM tag the applet may restart its running.
allows us to specify the list of arguments for the Syntax:
applets. Applets access their attributes with the public void start( )
getParameter() method. {
Statements ;
Applet Life Cycle }
Idle State:
When an applet is loaded it undergoes a series An Applet moves to this state when the
of changes in its state. An Applet can be in currently executed applet is minimized or when
any of the following states: the user goes to another page. At this point the
1. New Born state stop() method is invoked. The idle state halts
2. Running state the applet temporarily. From the idle state the
3. Idle state applet can move to the running state. The stop()
4. Dead or Destroyed state method can be called multiple times in the life
All these states are known as applet life cycle. cycle of applet.
Syntax:

public void stop()


{
Statements;
}
Dead State:
An applet can enter into this state by calling the
destroy() method. This method can bring an
applet to dead state. The destroy() method is
called only one time in the life cycle of Applet.
In this state, the applet is removed from
memory.
Syntax
New Born State
An applet enters into initialization state when public void destroy()
the applet is loaded into the browser by calling {
its init() method. The init() method is called Statements;
only one time in the life cycle on an applet. The }
init() method can receive the parameters Display State:
through the PARAM tag of html file. By using This state is not a part of the Applet life cycle.
this we can initialize the values. The applet is said to be in display state when
Syntax: the paint () method is called. This method can
public void init() display the output on the screen. This method
{ can be called any number of times.
Statements • Overriding paint() method is a must
} when we want to draw something on the
applet window.
• paint() method takes Graphics object as
argument. This method can be called

ANDHRA LOYOLA COLLEGE P a g e | 17


B.SC-III Year III-Semester OOP using JAVA

automatically each time when the applet


window is redrawn i.e. when it is
maximized from minimized state or
resized. It can also be invoked by
calling “repaint()” method.
Syntax:

public void paint(Graphics g)


{
Statements;
}

ANDHRA LOYOLA COLLEGE P a g e | 18

You might also like