0% found this document useful (0 votes)
16 views33 pages

Java Unit-3

The document provides an overview of Java packages, including Java API packages and user-defined packages, detailing how to create and access them. It explains the concept of applets, their lifecycle, and differences between applets and applications, along with the advantages of using applets. Additionally, it covers the applet lifecycle methods, how to create a simple applet, and the use of the applet tag in HTML.

Uploaded by

bkcda432
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views33 pages

Java Unit-3

The document provides an overview of Java packages, including Java API packages and user-defined packages, detailing how to create and access them. It explains the concept of applets, their lifecycle, and differences between applets and applications, along with the advantages of using applets. Additionally, it covers the applet lifecycle methods, how to create a simple applet, and the use of the applet tag in HTML.

Uploaded by

bkcda432
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BSC-II Semester-IV

[Link]. II Semester IV
Paper - I
UNIT – 3

1.1 Packages : Package is collection of related classes and interfaces. We can easily access the classes and
interfaces in a package in a program by importing that package into that program. There are two types
of java packages

3.1.1 Java API Packages : The following are the java API packages.

[Link] : It includes classes for primitive types, strings, math functions, threads and exceptions. These
are automatically imported.

[Link] : It includes classes for vectore, hash tables, random numbers, date etc.

[Link] : Input/Output support classes

[Link] : Classes for GUI interface like windows, buttons, menu

[Link] : classes for networking

[Link] : classes for applets

3.1.2 User defined Packages: Creating Packages :

We must first declare the name of the package using the package keyword followed by a package name.
This must be the first statement in program. Then we define class
Example
Package firstPackage;
Public class FirstClass
{
//body of class
}
Here the package name is firstPackage. The class FirstClass is part of this package. The program will be
saved as [Link] and stored in directory firstPackage.
The following are the steps for creating our own package :
1 Declare the package as
Package packageName;
2 Define the class to be put in the package and declare it public.
3 Create subdirectory named packageName
4 Store the program [Link] in the subdirectory
5 Compile the program. It creates .class file in subdirectory.

3.1.3 Accessing Package :


The import statement can be used to access the list of packages for a particular class.
Syntax:
Import package1[.package2][.package3].className;

Package1 is the name of the top level package, package2 is the name of package inside the package1 and
so on.
Example :
Shivaji Science College, Nagpur
BSC-II Semester-IV

Import [Link];
or
Import firstPackage.*;
package package1;
public class ClassA
{
public void displayA()
{
[Link]("class A");
}
}
3.1.4 Adding a class to Package :
Consider the following package :
package p1;
public class A
{
//body of A
}
The package p1 contains one public class by name A. Suppose we want to add another class B to this
package.
This can be done as follows:
1. Define the class and make it public.
2. Place the package statement package p1; before the class definition as follows.
package p1;
public class B
{
// body of B
}
3. Store this as [Link] file under p1 subdirectory.
4. Compile [Link] file. This will create a [Link] file and place it in the directory p1.

We can also add a non public class to a package using the same procedure.
The package p1 will contain both the classes A and B.
A statement import p1.*; will contain both of them.
package p;
public class A
{
void displayA()
{
[Link]("a1");
}
}
package p;
class B
{
void b1()
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]("b1");
}
}
package p;
public class C
{
void c1()
{
[Link]("c1");
}
}

import p.*;
public class PackageDemo
{
public static void main(String args[])
{
B b = new B();
b.b1();
C c= new C();
c.c1();
}
}

Impact of access modifiers in packages :


1. Use public if the field is to be visible everywhere.
2. Use protected if the field is to be visible everywhere in the current package and also subclasses in other
packages.
3. Use private protected if the field is to be visible only in subclasses, regardless of packages.
4. Use private if the field is not to be visible anywhere except in its own class.

Import Statment :
We can easily access the classes and interfaces in the same package but we can not directly refer to a class or
interface in a different package. In such case we have to specify a fully qualified name for a class or
interface. we can use the import statement in java source file to import classes from packages and use them
without qualifying the package.
There are 3 different ways to refer to class that is present in different package

1. Using fully qualified name (But this is not a good practice.)

Class MyDate extends [Link]


{
//statement;
}

2. import the only class you want to use.

Shivaji Science College, Nagpur


BSC-II Semester-IV

import [Link];

Class MyDate extends Date


{
// statement.
}

3. import all the classes from the particular package

import [Link].*;
class mydate extends Date
{
//statement;
}
Static import : It is used to import static member of a class. We know that static member are referred in
association with its class name outside the class. Using static import, it is possible to refer to the static
member directly without its class name. There are two general form of static import statement.
1. The first form of static import statement, import only a single static member of a class
Syntax
import static [Link]-member-name;
Example
import static [Link]; //importing static method sqrt of Math class

2. The second form of static import statement imports all the static member of a class
Syntax
import static [Link]-type-name.*;
Example
import static [Link].*; //importing all static member of Math class
Example without using static import
public class Test
{
public static void main(String[] args)
{
[Link]([Link](144));
}
}
Example using static import
import static [Link].*;
public class Test
{
public static void main(String[] args)
{
[Link](sqrt(144));
}
}

3.2 APPLETS
There are two kinds of Java programs, applications (also called stand-alone programs) and Applets. An
Applet is a small Internet-based program that has the Graphical User Interface
(GUI), written in the Java programming language. Applets are designed to run inside a web browser or in
applet viewer to facilitate the user to animate the graphics, play sound, and design the GUI components such
as text box, button, and radio button. When applet arrives on the client, it has limited access to resources, so
Shivaji Science College, Nagpur
BSC-II Semester-IV

that it can produce arbitrary multimedia user Interface and run complex computation without introducing the
risk of viruses or breaching data integrity.
To create an applet, we extend the “[Link]” class And by overriding the methods of
[Link], new functionality can be placed into web pages. Applets are compiled using javac compiler
and it can be executed by using an appletviewer or by embedding the class file in the HTML (Hyper Text
Markup Languege) file.

3.2.1 Difference between applet and application


A list of differences between applet and application are given below:

Applet Application
1. Applets as previously described, are the Applications are larger programs.
small programs
2 Applets don't have the main method Application execution starts with the main
method.
3 Applets are designed just for handling the java applications are designed to work with the
client site problems. client as well as server.
4 Applets are typically used. Applications are designed to exists in a
secure area.

3.2.2 Applet Class

The [Link] package is the smallest package in Java API(Application Programming Interface). The
Applet class is the only class in the package. The Applet class has many methods that are used to display
images, play audio files etc but it has no main() method. Some of them were explained below that give you
the knowledge about Applets and their behavior.
init() : This method is used for whatever initializations are needed for your applet. Applets can have a
default constructor, but it is better to perform all initializations in the init method instead of the default
constructor.
start() :This method is automatically called after Java calls the init method. If this method is overwritten,
code that needs to be executed every time that the user visits the browser page
that contains this applet.
stop() : This method is automatically called when the user moves off the page where the applet sits. If your
applet doesn't perform animation, play audio files, or perform calculations in
a thread, you don't usually need to use this method.
destroy(): Java calls this method when the browser shuts down.

3.2.4 Advantages of Applet :


Following are the advantages of a Java Applet:
• The most important feature of an Applet is, It is truly platform independent so there is no need of
making any changes in the code for different platform i.e. it is simple to
make it work on Linux, Windows and Mac OS i.e. to make it cross platform.
• The same applet can work on "all" installed versions of Java at the same time, rather than just the
latest plug-in version only.
• It can move the work from the server to the client, making a web solution more scalable with the
number of users/clients.
• The applet naturally supports the changing user state like figure positions on the chessboard.
• Applets improves with use: after a first applet is run, the JVM is already running and starts quickly.

Shivaji Science College, Nagpur


BSC-II Semester-IV

• Applets can be used to provide dynamic user-interfaces and a variety of graphical effects for web
pages.

3.2.5 Applet Lifecycle :


Every java Applet inherits a set of default behaviors’ from the Applet class. As a result, when an applet is
loaded it undergoes a series of changes in its state. Following are the states in applets
lifecycle.

1) Born or Initialization state:


An applet begins its life when the web browser loads its classes and calls its init() method. This method is
called exactly once in Applets lifecycle and is used to read applet parameters. Thus, in the init() method one
should provide initialization code such as the initialization of variables.
Example :
public void init()
{
//initialisation
}

2) Running State:
Once the initialization is complete, the web browser will call the start() method in the applet. This method
must called atleat once in the Applets lifecycle as the start() method can also be
called if the Applet is in “Stoped” state. At this point the user can begin interacting with the applet.
Example :
public void start()
{
//Code
}

3) Stopped State:
The web browser will call the Applets stop() method, if the user moved to another web page while the applet
was executing. So that the applet can take a breather while the user goes off and
explores the web some more. The stop() method is called atleast once in Applets Lifecycle.
Example :
publc void stop()
{
//Code
Shivaji Science College, Nagpur
BSC-II Semester-IV

}
4) Dead State:
Finally, if the user decides to quit the web browser, the web browser will free up system resources by killing
the applet before it closes. To do so, it will call the applets destroy() method. One can override destroy() to
perform one-time tasks upon program completion. for example, cleaning up threads which were started in
the init() method.

Example :
public void destroy()
{
// Code
}

Note: If the user returns to the applet, the web browser will simply
call the applet's start() method again and the user will be back into
the program.

5) Display State :
Applet moves to the display state whenever it has to perform the output operations on the screen. This
happens immediately after the applet enters into the running state. The paint() method is
called to accomplish this task.
Example :

public void paint(Graphics g)


{
//Display Statements
}
3.2.6 MY FIRST APPLET

Example.
import [Link].*;
import [Link].*;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("My First Applet",40,40);
}
}
• Save the file as [Link]
• Compile the file using javac [Link]

Here is the illustration of the above example,


• In the first line we imports the Abstract Window Toolkit(AWT) classes as Applet interact with the
user through the AWT, not through the console –based I/O classes. The AWT contains support for a
window based graphical interface.
• In the second line we import the Applet package, which contains the class “Applet”. As every applet
that we create is the subclass of Applet.
• The next line declares the class SimpleApplet. This class must be declared in public, because it will
be accessed by code that is outside the program.

Shivaji Science College, Nagpur


BSC-II Semester-IV

• Inside simpleApplet, paint() method is declared. This method is defined by the AWT and must be
overridden by the Applet. Method paint() is called each time that the applet must redisplay its output.
This paint() method has parameter of type “ Graphics”. This parameter contains the graphics context,
which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.
• Inside paint() method is a call to drawstring(), which is a member of the Graphics class. This method
output a String beginning at specified X, Y locations.

3.2.7 How to run an Applet?


There are two ways in which one can run an applet, as follows
1) Executing the applet within a java-compatible web browser.
2) Using an applet viewer, such as the standard SDK tool, “appletviewer”. An applet viewer executes your
applet in a window. This is generally the fastest and
easiest way to test your applet.

To execute an applet in a web browser, you need to write a short HTML text file that contains the
appropriate APPLET tag.
Example
<html>
<body>
<applet code="[Link]" width=200 height=100>
</applet>
</body>
</html>

Save this code in text file with extension .html say [Link].
Compile the file using javac [Link]
On successful compilation of [Link] file, execute this file using appletviewer
[Link] or just open this html file directly.
The output of above example appears as shown in the following
figure:

Insted of creating different text file for html code one can write above program as follows
import [Link].*;
import [Link].*;
/* <applet code="SimpleApplet" width=200 height=100>
</applet>
*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("My First Applet",40,40);
Shivaji Science College, Nagpur
BSC-II Semester-IV

}
}

Save the file as [Link]


Compile the file using javac [Link]
On successful compilation, execute the this file using appletviewer [Link]
The output remains same.

3.2.8 Building an applet code:


i) Applet code uses the series of two classes, namely Applet and Graphics from java class library.
ii) Applet class which is contained in the [Link] package provides life and behaviour to the applet
through its methods such as init(), start(), and paint().
iii) When an applet is loaded, java automatically calls a series of applet class methods for starting,
running and stopping the applet code.
iv) The applet class therefore maintains the lifecycle of an applet.
v) The paint() method of the applet class, when it is called, actually display the result of applet code
on the screen.
vi) The output may be text, graphics or sound.
vii) The paint() method, which requires a Graphics object as an argument, is defined as follows:
public void paint(Graphics g)
viii) This requires that the applet code imports the [Link] package that contains the Graphics class.
ix) All output operations of an applet are performed using the methods defined in the Graphics class.

3.2.9 Applet Tag

The Applet tag is used to start an applet from both HTML document and from applet viewer.
An applet viewer will execute each Applet tag that it finds in a separate window, while web browsers like
Netscape Navigator, Internet Explorer and HotJava will allow many applets in a single page.
The <applet....> tag included in the body section of HTML file supplies the name of the applet to be loaded
and tells the browser how much space the applet requires

The synatax for the standard Applet tag is as follows


< applet
[codebase=codebaseURL]
code=[Link]
[ALT=alternative text]
[name=AppletInstanceName]
Width=pixels
Height= pixels
[align= alignment]
[vspace=pixels]
[hspace=pixels]
>
[<param name=”Attributename” value =”Attribute value”]
[<param name=”Attributename” value =”Attribute value”]
........
[HTML displayed in the absence of java]
</applet>

Explanation :

Shivaji Science College, Nagpur


BSC-II Semester-IV

Codebase: Codebase is an optional attribute that specifies the base URL of the applet code, which is
the directory that will be searched for te applet’s executable class file. The HTML document’s URL
directory is used as the CODEBASE if this attribute is not specified. The CODEBASE if this
attribute is not specified. The CODEBASE does not have to be on the host from which the HTML
document was read.
Code: code is required attribute that gives the name of the file containing the applets compiled .class
file. This file is relative t the code base URL of the applet , which is the directory that the HTML file
whs in or th edirectory indicated by the CODEBASE if set.
ALT : The ALT tag is an optional attribute used to specify a short text message that should be
displayed if browser understand the APPLET tag but cant currently run java applet.
Name: Name is an optional attribute used to specify a name for the applet instance. Applets must be
named in order for other applets on the same page to find them by name and communicate with them.
To obtain an applet by name, use getAppet(), which is defined by the AppletContext interface.
Param name and value : The PARAM tag allows us to specify applet specific arguments in an
HTML page. Applets access their attributes with the getParameter() method.

3.2.10 Passing Parameters to Applet


One can supply user-defined parameters to an applet using <param.....> tag. Each <param....> tag has a
name attribute such as color and a value attribute such as red. Inside the applet code, the applet can refer to
that parameter by name to find its value.
For e.g. the color of the text can be changed to red by an applet using a <param...> tag as follows
<applet....>
<param=color value = “red”>
</applet>

Similarly we can change the text to be displayed by an applet by supplying new text to the applet through a
<param....>tag as shown below.
<param name=text value = “xyz” >

Passing a parameters to an applet is similar to passing parameters to main() method using command line
arguments. To set up and handle parameters, we need to do two things.
1) Include appropriate <param.....> tags in the HTML document.
2) Provide code in the applet to pass these paraments.
Parameters are passed to an applet when it is loaded. We can define the init() method in the applet to get
hold of the parameters defined in the <param> tags. This is done using the getparameter() method, which
takes one string argument representing the name of the parameter and returns a string containing the value of
that parameter.

3.2.11 Types of Applets

As we can embed applet into web pages in two ways i.e. by writing our own applet and then embed into web
pages or by downloading it from a remote computer system and then embed it
into webpage.
An applet developed locally and stored in a local system is known as local applet. Therefore when webpage
is trying to find local applet it does not need the internet connection. As we can embed applet into web
pages in two ways i.e. by writing our own applet and then embed into web pages or by downloading it from
a remote computer system and then embed it into webpage.

A remote applet is that which is developed by some one else and stored on a remote computer connected
to the internet. If our system is connected to the internet then we can download it from remote computer and
run it. In order to locate and load a remote applet, we must know the applet’s address on the web. This
address is known as Uniform Resources locator(URL) and must be specified in applet’s document.
Shivaji Science College, Nagpur
BSC-II Semester-IV

//Example 1
import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>
<param name="message" value "Hi">
</applet>
*/
public class FirstApplet1 extends Applet
{
public void paint(Graphics g)
{
String str = getParameter("message");
[Link]("Hello Good Morning "+str,60,30);
}
}

//Example 2
import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>
</applet>
*/
public class FirstApplet3 extends Applet
{
public void paint(Graphics g)
{
int a=10;
int b=12;
int c=a*b;
[Link]("Sum = "+ [Link](c),60,30);
}
}

//Applet program to find factorial


import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>
</applet>
*/
public class FirstApplet4 extends Applet
{
public void paint(Graphics g)
{
int i=1;
int fact=1;
for(i=1;i<=5;i++)
fact=fact*i;
[Link]("Factorial of 5 = "+ [Link](fact),60,30);
Shivaji Science College, Nagpur
BSC-II Semester-IV

}
}

//Applet to draw arc


import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>
</applet>
*/
public class FirstApplet5 extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](120,20,560,560,0,180);
}
}

//Applt to draw polygon


import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>

</applet>
*/
public class FirstApplet6 extends Applet
{
public void paint(Graphics g)
{
int n=5;
int xdata[]={10,60,90,140,190};
int ydata[]={100,10,140,90,10};
[Link]([Link]);
[Link](xdata,ydata,n);
}
}

//Applet to fill polygon


import [Link].*;
import [Link].*;
/*
<APPLET CODE="[Link]" width=400 height=200>
</applet>
*/
public class FirstApplet7 extends Applet
{
public void paint(Graphics g)
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
int n=5;
int xdata[]={10,60,90,140,190};
int ydata[]={100,10,140,90,10};
[Link]([Link]);
[Link](xdata,ydata,n);
}
}

//Applet to draw stop signal


import [Link].*;
import [Link].*;
/*
<applet CODE="[Link]" width=400 height=200>
</applet>
*/
public class FirstApplet8 extends Applet
{
public void paint(Graphics g)
{
int n=4;
int xdata[]={160,160,300,300};
int ydata[]={20,450,450,20};
[Link]([Link]);
[Link](xdata,ydata,n);
//to draw stop signal
[Link]([Link]);
[Link](180,50,100,100);
[Link]([Link]);
[Link]("Stop ",210, 105);
}
}

// Example to illustrate Applet Lifecycle


import [Link].*;
import [Link].*;
/* <applet code="AppletTest" width=200 height= 100>
</applet>
*/
public class AppletTest extends Applet
{
public void init()
{
[Link]("Applet Initialised...");
setBackground([Link]);
}
public void start()
{
[Link]("Applet Started....");
}
public void stop()
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]("Applet Stopped....");
}
public void destroy()
{
[Link]("Applet Destryoed....");
}
public void paint(Graphics g)
{
[Link]("Applet Text",200,400);
showStatus("This is shown in Status.");
}
}

// Example to illustrate Applet Lifecycle


import [Link].*;
import [Link].*;
/* <applet code="Sample" width=200 height= 100>
</applet>
*/
public class Sample extends Applet
{
String msg;
public void init()
{
setBackground([Link]);
setForeground([Link]);
msg = "Inside init()-";
}
public void start()
{
msg += "Inside start()-";
}
public void paint(Graphics g)
{
msg +="Inside paint()-";
[Link](msg,10,30);
showStatus("This is shown at status");
}
}

// Write an applet that accepts a value from user and display it [Link]
import [Link].*;
import [Link].*;
public class accdisp extends Applet
{
TextField T1;
public void init()
{
T1=new TextField(20);
add(T1);
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link](" ");
}
public void paint(Graphics g)
{
String str;
[Link]("Enter Text",0,25);
str=[Link]();
[Link](str,100,100);
}
public boolean action(Event e, Object o)
{
repaint();
return true;
}
}

//Write an applet that accepts two numbers from the user and displays all the numbers between them.

import [Link].*;
import [Link].*;
public class betno extends Applet
{
TextField T1,T2;
public void init()
{
T1=new TextField(10);
T2=new TextField(10);
add(T1);
add(T2);
[Link]("0");
[Link]("0");
}
public void paint(Graphics g)
{
int a,b;
String str;
FontMetrics F=[Link]();
[Link](" Enter number",0,25);
[Link] ([Link]);
str=[Link]();
a=[Link](str);
str=[Link]();
b=[Link](str);
int cur=50;
int max=(a>b)?a:b;
int min=(a<b)?a:b;
for(int i=min+1;i<max;i++)
{
cur=cur+[Link]();
[Link]("Number are"+ i, 0,cur+30);
}
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

public boolean action(Event e,Object o)


{
repaint();
return true;
}
}

3.2.12 Applet to Applications


Applets are programs which run on web browser and Application means the stand alone program in a
computer. In Java we can convert Applets to Application and Application to Applet. Using this idea we can
make any program run as either applet or as an application. Following are the steps for converting applets to
Application.
Step 1:
Change init() method's name to the constructor. Java Applets contains init() method which is used for
initializing the applet, this method should be changed to constructor for that class. This involves removing
void(return type) of init(), because constructor don't return anything.
e.g. public void init() should be changed to
Application()
Step 2:
Replace "extends Applet" with "extends Frame" for the class.
e.g. public class Application extends Applet should be changed to
public class Application extends Frame
Step 3:
Create new main() method. Create object of the class in that method and set size of the frame and different
properties as follows.
public static void main(String[] args)
{
Application app=new Application();
[Link](400,400);
[Link](true);
[Link](new FlowLayout());
}
Step 4:
Delete "import" statement for class Applet.
Step 5:
Add WindowListener's method to handle window events.
Step 6:
HTML is not required (delete it)

3.3 MULTI THREADING


Multithreading is a conceptual programming concept where a program ( process) is divided
into two or more subprograms (process), which can be implemented at the same time in
parallel. A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of execution.

3.3.1 Benefits of Multithreading


[Link] programmers to do multiple things at one time
[Link] can divide a long program into threads and execute them in parallel which eventually
increases the speed of the program execution
[Link] performance and concurrency
[Link] access to multiple applications
Shivaji Science College, Nagpur
BSC-II Semester-IV

3.3.2 Thread Life Cycle:


During the life cycle of a thread, there are many states it can enter .

[Link] state – After the construction of Thread instance the thread is in this state but before the start()
method invocation. At this point, the thread is considered not alive.

2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable
state after the invoking of start() method but a thread can come again to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the
processor.

3. Running state – A thread is in running state that means the thread is presently executing. There are
numerous ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler
select a thread from runnable pool. It calls run() method

4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on
this state that means it cannot ever run again.

5. Blocked(Waiting) state - A thread can enter in this state because of waiting the resources that are hold by
another thread.

3.3.4 Difference between multithreading and multitasking:

Multithreading Multitasking
1 It is programming concept in It is an operating system concept
which a program or a process is in which multiple tasks are
divided into two or more performed simultaneously.
subprograms or threads that are
executed at the same time in
parallel
2 It supports execution of multiple It supports execution of multiple
parts of a single program programs simultaneously.
simultaneously.
3 The processor has to switch The processor has to switch
between different parts or threads between different programs or
of a program. processes.
4 It is highly efficient. It is less efficient in comparison to
multithreading.
Shivaji Science College, Nagpur
BSC-II Semester-IV

5 A thread is smallest unit in Program or process is the smallest


multithreading. unit in a multitasking environment

3.3.5 Thread Creation and simple programs:


In Java, an object of the Thread class can represent a thread. Thread can be implemented by extending the
[Link] Class

Syntax: class MyThread extends Thread


{

}
• After declaration of thread class, we have to override run( ) method in class.
• Now we can create object of thread if needed.

In short we have to follow following these steps:


1. Extend the [Link] Class.
2. Override the run( ) method in the subclass from the Thread class to define the code executed by the
thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass
constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.

Example :
//Program to demonstrate the Multithreading concept
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
if (i==1) yield();
[Link]("From Thread A : "+i);
}

[Link]("Exit From Thread A ");


}
}

class B extends Thread


{
public void run()
{
for(int j=1; j<=5;j++)
{
[Link]("From Thread B : "+j);
if (j==3) stop();
}
[Link]("Exit From Thread B ");
}
}
class C extends Thread
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
public void run()
{
for(int k=1; k<=5;k++)
{
[Link]("From Thread C : "+k);
}
[Link]("Exit From Thread C ");
}
}

class MultithreadTestMethod
{
public static void main(String args[] )
{
A mythread1 = new A();
[Link]("Start thread A ");
[Link]();

B mythread2 = new B();


[Link]("Start thread B ");
[Link]();

C mythread3 = new C();


[Link]("Start thread C ");
[Link]();

}
}

Output :
From Thread A : 1
From Thread B : 1
From Thread B : 2
From Thread B : 3
From Thread A : 2
From Thread B : 4
From Thread A : 3
From Thread B : 5
From Thread A : 4
Exit From Thread B
From Thread A : 5
Exit From Thread A
From Thread C : 1
From Thread C : 2
From Thread C : 3
From Thread C : 4
From Thread C : 5
Exit From Thread C
Press any key to continue . . .

Shivaji Science College, Nagpur


BSC-II Semester-IV

3.3.6 Thread Methods :

Method Name Description


1. void start() This method causes this thread to begin execution; the Java
Virtual Machine calls the run method of this thread.
2. void run() This method encapsulates the functionality of thread. This
method is always overridden.
3. static void sleep(long This method causes the currently executing thread to sleep
millis) (temporarily cease execution) for the specified number of
milliseconds, subject to the precision and accuracy of system
timers and schedulers.
4. static void yield() This method causes the currently executing thread object to
temporarily pause and allow other threads to execute.
5. void setPriority(int This method changes the priority of this thread.
newPriority)
6. public void suspend() This method puts a thread in the suspended state and can be
resumed using resume() method.
7. public void stop() This method stops a thread completely.
8. public void resume() This method resumes a thread, which was suspended using
suspend() method.
9. public void wait() Causes the current thread to wait until another thread invokes
the notify().
10. public void notify() Wakes up a single thread that is waiting on this object's monitor

//Program to demonstrate the ThreadMethods concept


import [Link].*;
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{ if (i==1) yield();
[Link]("\t From Thread A :i = "+i);
}
[Link]("Exit From Thread A ");
}
}

class B extends Thread


{
public void run()
{

Shivaji Science College, Nagpur


BSC-II Semester-IV

for(int j=1; j<=5;j++)


{
[Link]("\tFrom Thread B : j = "+j);
if (j==3) stop();
}
[Link]("Exit From Thread B ");
}
}

class C extends Thread


{
public void run()
{
for(int k=1; k<=5;k++)
{
[Link]("\tFrom Thread C : k = "+k);
if (k==1)
try
{
sleep(1000);
}

catch (Exception e)
{
}
}
[Link]("Exit From Thread C ");
}
}

class ThreadMethods
{
public static void main(String args[] )
{
A threadA = new A();
B threadB = new B();
C threadC = new C();
[Link]("Start Thread A ");
[Link]();
[Link]("Start Thread B ");
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]();
[Link]("Start Thread C ");
[Link]();
[Link]("End of main Thread ");
}
}

3.3.7 Thread Exceptions :


Java run system will throw IllegalThreadStateException whenever we attempt to invoke a method that a
thread can not handle in the given state. For example, a sleeping thread can not deal with the resume()
method because a sleeping thread can not receive any instructions. The same is true with suspend() method
when it is used on a blocked thread.
Whenever we call a thread method that is likely to throw an exception , we have to supply an appropriate
exception handler to catch it
Syntax :
Catch (ThreadDeath e)
{
……..
……..
}

Catch (Exception e)
{
……..
……..
}
Catch (InterruptedException e)
{
……..
……..
}

Catch (IllegalArgumentedException e)
{
……..
……..
}

3.3.8 Thread Priority :


In java, each thread is assigned priority, which affects the order in which it is scheduled for running. The
threads of the same priority are given equal treatment by the java scheduler and therefore they share the
processor on a first come first serve basis.
The priority of thread can be given using the setPriority method() as follows :
[Link](intNumber);
The intNumber is integer number between 1 to 10. The Thread class defines following priority constants.
MIN_PRIORITY =1
NORM_PRIORITY =5
MAX_PRIORITY =10
Shivaji Science College, Nagpur
BSC-II Semester-IV

The default setting is NORM_PRIORITY.

Whenever multiple threads are ready for execution, the jave system chooses the highest priority thread and
executes it. For a thread of lower priority to gain control, one of the following things should happen:
i) It stops running at the end of run().
ii) It is made to sleep using sleep().
iii) It is to wait using wait().
However, if another thread of a higher priority comes along, the currently running thread will be preempted
by the incoming thread, forcing the current thread to move to the runnable state.

//Program to demonstrate the ThreadPriority concept


import [Link].*;
class A extends Thread
{
public void run()
{
[Link](" ThreadA started ");
for(int i=1; i<=4;i++)
{
[Link]("\t From Thread A :i = "+i);
}
[Link]("Exit From Thread A ");
}
}

class B extends Thread


{
public void run()
{ [Link](" ThreadB started ");
for(int j=1; j<=4;j++)
{
[Link]("\tFrom Thread B : j = "+j);
}
[Link]("Exit From Thread B ");
}
}

class C extends Thread


{
public void run()
{ [Link](" ThreadC started ");
for(int k=1; k<=4;k++)
{
[Link]("\tFrom Thread C : k = "+k);

}
[Link]("Exit From Thread C ");
}
}

class ThreadPriority
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

public static void main(String args[] )


{
A threadA = new A();
B threadB = new B();
C threadC = new C();
[Link](Thread.MAX_PRIORITY);
[Link]([Link]()+1);
[Link](Thread.MIN_PRIORITY);

[Link]("Start Thread A ");


[Link]();
[Link]("Start Thread B ");
[Link]();
[Link]("Start Thread C ");
[Link]();
[Link]("End of main Thread ");
}
}

Output :
Start Thread A
Start Thread B
ThreadA started
ThreadB started
From Thread A :i = 1
Start Thread C
From Thread A :i = 2
From Thread A :i = 3
From Thread B : j = 1
From Thread B : j = 2
From Thread B : j = 3
From Thread B : j = 4
Exit From Thread B
From Thread A :i = 4
ThreadC started
End of main Thread
From Thread C : k = 1
From Thread C : k = 2
Exit From Thread A
From Thread C : k = 3
From Thread C : k = 4
Exit From Thread C
Press any key to continue . . .

3.3.9 Synchronization :
Since all the threads in program share the same memory space, two or more threads in a program may
try to access the same method . For example , the cashier of three branches oa a firm ( three threads) may
simultaneously access the method that credits an amount into the common account of the firm . Data
corruption may occur if the access to a method by many threads is not properly regulated by way of
synchronizing the access to such a shared method.

Shivaji Science College, Nagpur


BSC-II Semester-IV

The access to a method shall be synchronized by specifying the synchronized keyword as a modifier in
the method declaration.
Syntax :
synchronized void update()
{
……….
………..
}

When a threads starts executing a synchronized instance method , it automatically gets a logical lock on
the object that contains the synchronized method. This lock will remain as long as that thread is executing
that synchronized method . When the lock is present, no other thread will be allowed entry into that object.
The lock will be automatically released, when that thread completes the execution of that synchronized
method. This is how the JVM carefully coordinates the access to a common resource by multiple threads.
Deadlock condition : An interesting situation may occur when two or more threads are waiting to gain
control of a resource. Due to some reasons, the condition on which the waiting threads rely on to gain
control does not happen. This result is known as deadlock. For example, assume that the thread A must
access method1 before it can release method2, but the thread B cannot release method1 until it gets hold of
method2. Because these are mutually exclusive conditions, a deadlock occurs.

3.3.10 Implementing the ‘RUNNABLE’ interface


We can create threads in two ways.
1. By using the extended Thread class.
2. By implementing the Runnable interface.

The Runnable interface declares the run() method that is required for implementing threads in our
programs. We must performs the following steps
i) Declare the class as implementing the Runnable interface.
ii) Implement the run() method.
iii) Create a thread by defining an object that is instantiated from this “runnable” class as the target of the
thread.
iv) Call the start() method to run the thread.

3.3.11 Inter-Thread Communication :


Inter-thread communication can be defined as the exchange of messages between two or more threads.
The transfer of messages take place before or after the change of state of a thread. For example, an active
thread may notify to another suspended thread just before switching to the suspended state. Java implements
inter-thread communication with the help of following three methods :

i) notify() : Resumes the first thread that went into the sleep mode.
Syntax :
final void notify()

ii) notifyall() : Resumes all the threads that are in sleep mode.
Syntax :
final void notifyall()

iii) wait() : Sends the calling thread into the sleep mode. This thread can now be activated only by notify()
or notifyall() methods.

Syntax :
Shivaji Science College, Nagpur
BSC-II Semester-IV

final void wait()

These methods can not be overridden. All the three methods throw InterruptedException.

3.4 EXCEPTION HANDLING


An exception is a condition that is caused by a run time error in the program. When the java interpreter
encounters an error such as dividing an integer by zero, it creates an exception object and throws it.
If the exception object is not caught and handled properly, the interpreter will display an error message and
will terminate the program. If we want the program to continue with the execution of remaining code, then
we should try to catch the exception object thrown by the error condition and then display appropriate
message for corrective actions. This task is known as exception handling. Exception handling is basically
use five keyword as follows:
• Try
• Catch
• Throw
• Throws
• finally

3.4.1 Types of Errors :


1. Compile time errors
Compiler time error means Java compiler identify the syntax error at the time of compilation. And without
successfully compilation, compiler does not create .class file. That means we have to compile the program
which should be error free and then compiler creates .class file of the program and then we can run the
program.
The common problems are:
• Missing braces
• Missing semicolon
• Missing double quote in string
• instead of == operator
and so on.

2. Run time errors


Several time program may compile successfully and compiler creates the .class file of the program but when
the time of running the program, it shows the error and that type of error called run time error.
The common problems are:
• Divide by zero
• Conversion of invalid string to number
• access the element that is out of bound of an array
• Passing the parameters with invalid range.
and so on.

For example:
write a program to find out division of two numbers.
class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b;
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]("Division is"+c);
}
}
Output:
C:\cc>javac [Link]
C:\cc>java Try1
Exception in thread "main" [Link]: /
by zero at [Link]([Link])

3.4.2 Exception Handling :


try…catch:
If a method is going to resolve potential exception internally, the line of code that could generate the
exception is placed inside a try block. There may be other code inside the try block, before and/or after the
risky line(s) - any code that depends upon the risky code's success should be in the try block, since it will
automatically be skipped if the exception occurs.

Syntax :
try
{
code
risky/unsafe code
code that depends on the risky code succeeding
}

There is usually at least one catch block immediately after the try block
A catch block must specify what type of exception it will Catch

Syntax :
catch (ExceptionClassName exceptionObjectName)
{
code using methods from exceptionObjectName
}

• there can be more than one catch block, each one marked for a correct exception class
• the exception class that is caught can be any class in the exception hierarchy, either a general (base)
class, or a very correct (derived) class
• the catch block(s) must handle all checked exceptions that the try block is known to throw unless you
want to throw that exception back to the method.
• it is possible to have a try block without any catch blocks if you have a finally block but any checked
exceptions still need to be caught, or the method needs to declare that it throws them.

If an exception occurs within a try block, execution jumps to the first catch block whose exception class
matches the exception that occurred. Any steps remaining in the try block are skipped. If no exception
occurs, then the catch blocks are skipped.
If declare a variable within a try block, it will not exist outside the try block, since the curly braces define the
scope of the variable. You will often need that variable later, if nowhere else other than the catch or finally
blocks, so you would need to declare the variable before the try.
If you declare but don't initialize a variable before a try block, and the only place you set a value for that
variable is in the try block, then it is possible when execution leaves the try ... catch structure that the
variable never received a value. So, you would get a "possibly uninitialized value" error message from the
compiler, since it actually keeps track of that sort of thing. Usually this happens with object references; you
would also generally initialize them to null.
Shivaji Science College, Nagpur
BSC-II Semester-IV

//to demonstrate try..catch block


public class demo
{
public static void main(String[] args)
{
int ans1, ans2;
int a = 2, b = 2, c = 0;

try
{
ans1 = a/b;
[Link]("a/b = " + ans1);
ans2 = a/c;
[Link]("a/c = " + ans2);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic
Exception!");
}
[Link]("demo is over");
}
}
Output:
C:\>set path=C:\Java\jdk1.5.0_01\bin
C:\>javac [Link]
C:\>java demo
a/b = 1
Arithmetic Exception!
demo is over

Code Explanation –
The program will print the first result, and then not succeed while performing the division for the second
equation. Execution will step to the catch block to print our message on the screen

Example -
The prior example used a RuntimeException, which your
code is not obligated to handle. Most methods in the I/O classes throw IOException, which is an exception
that you must handle.
Following program shows the use of IOException.

import [Link];
public class demo
{
public static void main(String[] args)
{
int num = 0;
num = [Link]();
try
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
num = [Link]();
[Link]("You entered " + (char) num);
}
catch (IOException e)
{
[Link]("IO Exception occurred");
}
}
}
Output:
C:\>javac [Link]
[Link]: unreported exception [Link]; must be caught or declared to be thrown
num = [Link](); // comment out this line
^
1 error
Code Explanation:
The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The
second read attempt is within a try block, as it should be.
There is no way we can force an IOException from the keyboard to test the catch block.

3.4.3 Using Multiple catch Blocks


It is possible that a statement might throw more than one kind of exception
you can list a sequence of catch blocks, one for each possible exception
remember that there is an object hierarchy for exceptions
class demo
{
public static void main (String args [])
{
int A[ ] = new int [5];
try
{
for (int c = 0; c <5; c++)
{
//do nothing
}
for (int c = 0; c <5; c++)
{
A[c] = c/ c;

}
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link] ("Array out of bound ");
}
catch (ArithmeticException e)
{
[Link] ("Zero divide error");
}
}
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

Output:
C:\>javac [Link]
C:\>java demo
Zero divide error
C:\>

3.4.4 Finally Block


To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try and
catch blocks The code in the finally block will almost always execute, even if an unhandled exception
occurs; in fact, even if a return statement is encountered
if an exception causes a catch block to execute, the finally block will be executed after the catch
block
if an uncaught exception occurs, the finally block executes, and then execution exits this method and
the exception is thrown to the method that called this method

Syntax :
try
{
risky code/ unsafe code block
}
catch (ExceptionClassName exceptionObjectName)
{
code to resolve problem
}
finally
{
code that will always execute
}

Example:
public class demo
{
public static void main(String args[])
{
try
{
[Link]("Try Block before the error.");
[Link](1/0);
[Link]("Try Block after the error.");
}
catch([Link] e)
{
[Link]("Catch Block");

[Link]("A Stack Trace of the Error:");


[Link]();
//[Link]();
[Link]("The operation is not possible.");
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

finally
{
[Link]("Finally Block");
}
[Link]("demo is over");
}
}
Output:
C:\>javac [Link]
C:\>java demo
Try Block before the error.
Catch Block
A Stack Trace of the Error:
[Link]: / by zero
at [Link]([Link])
The operation is not possible.
Finally Block
demo is over

3.4.5 Throwing an Exception


You can throw an exception explicitly using the throw statement.
Example:
You need to throw an exception when a user enters a wrong student ID or password.
The throws clause is used to list the types of exception that can be thrown in the execution of a method in a
program.

Using the throw Statement


1. The throw statement causes termination of the normal flow of control of the java code and prevents the
execution of the subsequent statements.
2. The throw clause convey the control to the nearest catch block handling the type of exception object
throws.
3. If no such catch block exists, the program terminates.

The throw statement accepts a single argument, which is an object of the Exception class.

Syntax –
throw ThrowableObj
You can use the following code to throw the IllegalStateException exception:
class demo
{
static void tdemo()
{
try
{
throw new IllegalStateException ();
}
catch (NullPointerException e)
{
[Link] ("Not Caught by the catch block inside tdemo
().");
}
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

public static void main (String args[ ])


{
try
{
tdemo();
}
catch(IllegalStateException e)
{
[Link]("Exception Caught in:"+e);
}
}
}

Output
C:\>javac [Link]
C:\>java demo
Exception Caught in:[Link]
C:\>

3.4.5 Using the throws Statement


The throws statement is used by a method to specify the types of exceptions the method throws. If a method
is capable of raising an exception that it does not handle, the method must specify that the exception have to
be handled by the calling method.
This is done using the throws statement. The throws clause lists the types of exceptions that a method might
throw.

Syntax –
[< access specifier >] [< modifier >] < return type > < method name
> [< arg list >] [ throws <exception list >]

Example:
You can use the following code to use the throws statement:
class demo
{
static void throwMethod ( ) throws ClassNotFoundException
{
[Link] ("In throwMethod ");
throw new ClassNotFoundException ( );
}
public static void main (String args [ ])
{
try
{
throwMethod ( );
}
catch ( ClassNotFoundException e)
{

[Link] (" throwMethod has thrown an Exception :" +e);


}
}
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

Output
C:\>javac [Link]
C:\>java demo
In throwMethod throw Method has thrown an Exception :[Link] Not Found
Exception

Shivaji Science College, Nagpur

You might also like