Java Unit-3
Java Unit-3
[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.
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.
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();
}
}
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
import [Link];
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.
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.
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.
• Applets can be used to provide dynamic user-interfaces and a variety of graphical effects for web
pages.
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 :
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]
• 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.
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
}
}
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
Explanation :
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.
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.
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>
*/
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);
}
}
{
int n=5;
int xdata[]={10,60,90,140,190};
int ydata[]={100,10,140,90,10};
[Link]([Link]);
[Link](xdata,ydata,n);
}
}
[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.");
}
}
// 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
[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.
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
}
• After declaration of thread class, we have to override run( ) method in class.
• Now we can create object of thread if needed.
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);
}
{
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]();
}
}
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 . . .
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 ");
}
}
Catch (Exception e)
{
……..
……..
}
Catch (InterruptedException e)
{
……..
……..
}
Catch (IllegalArgumentedException e)
{
……..
……..
}
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.
}
[Link]("Exit From Thread C ");
}
}
class ThreadPriority
{
Shivaji Science College, Nagpur
BSC-II Semester-IV
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.
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.
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.
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
These methods can not be overridden. All the three methods throw InterruptedException.
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])
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
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.
}
}
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:\>
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");
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
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
Output
C:\>javac [Link]
C:\>java demo
Exception Caught in:[Link]
C:\>
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)
{
Output
C:\>javac [Link]
C:\>java demo
In throwMethod throw Method has thrown an Exception :[Link] Not Found
Exception