Unit - Iii: SKCW - Department of Computer Applications
Unit - Iii: SKCW - Department of Computer Applications
UNIT – III
DEFINING PACKAGE
Packages are containers for classes that are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into
new class definitions.
A package is a container of classes and interfaces. A package represents a directory that contains
related group of classes and interfaces. For example, when we write statemens like:
import java.io.*;
Here we are importing classes of java.io package. Here, java is a directory name and io is another
sub directory within it. The „*‟ represents all the classes and interfaces of that io sub directory.
We can create our own packages called user-defined packages or extend the available packages.
User-defined packages can also be imported into other classes and used exactly in the same way
as the Built-in packages.
ADVANTAGES OF PACKAGES:
Packages are useful to arrange related classes and interfaces into a group. This makes all
the classes and interfaces performing the same task to put together in the same package.
For example , in Java, all the classes and interfaces which perform input and output
operations are stored in java.io. package.
Packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.
The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java.util package and also there is another
Date class in java.sql package.
A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times. This reusability nature of packages
makes programming easy. Just think, the package in Java are created by JavaSoft people
only once, and millions of programmers all over the world are daily by using them in
various programs.
Built-in packages:
These are the packages which are already available in Java language. These packages provide all
most all necessary classes, interfaces and methods for the programmer to perform any task in his
programs. Since, Java has an extensie library of packages, a programmer need not think about
logic for doing any task. For everything, there is a method available in Java and that method can
be used by the programmer without developing the logic on his own. This makes the
programming easy. Here, we introduce some of the important packages of Java SE:
Java.lang: lang stands for language. This package got primary classes and interfaces essential
for developing a basic Java program. It consists of wrapper classes(Integer, Character, Float etc),
which are useful to convert primitive data types into objects. There are classes like String,
SttringBuffer, StringBuilder classes to handle strings. There is a thread class to create various
individual processes. Runtime and System classes are also present in java.lang package which
contain methods to execute an application and find the total memory and free memory available
in JVM.
Java.util: util stands for utility. This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections. There are also classes
for handling Date and Time operations.
Java.io: io stands for input and output. This package contains streams. A stream represents flow
of data from one place to another place. Streams are useful to store data in the form of files and
also to perform input-output related tasks.
Java.awt: awt stands for abstract window toolkit. This helps to develop GUI(Graphical user
Interfaces) where programs with colorful screens, paintings and images etc., can be developed. It
consists of an important sub package, java.awt.event, which is useful to provide action for
components like push buttons, radio buttons, menus etc.
Javax.swing: this package helps to develop GUI like java.awt. The „x‟ in javax represents that it
is an extended package which means it is a package developed from another package by adding
new features to it. In fact, javax.swing is an extended package of java.awt.
Java.net: net stands for network. Client-Server programming can be done by using this package.
Classes related to obtaining authentication for network, creating sockets at client and server to
establish communication between them are also available in java.net package.
Java.applet: applets are programs which come from a server into a client and get executed on
the client machine on a network. Applet class of this package is useful to create and use applets.
Java.text: this package has two important classes, DateFormat to format dates and times, and
NumberFormat which is useful to format numeric values.
Java.sql: sql stands structured query language. This package helps to connect to databases like
Oracle or Sybase, retrieve the data from them and use it in a Java program.
the
use of locks.
User-Defined packages:
Just like the built in packages shown earlier, the users of the Java language can also create their
own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as the Built-in packages.
The –d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in
the current directory. So, out package pack with Addition class is ready.
Program 3: Write a program to add one more class Subtraction to the same package pack.
//Adding one more class to package pack:
package pack;
public class Subtraction
{ private double d1,d2;
d2 = b;
}
public void difference()
{ System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
}
}
Compiling the above program:
Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
}
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs will not
exist in the current directory. Delete them from the current directory as they cause confusion for
the Java compiler. The compiler looks for byte code in Addition.java and Subtraction.java files
and there it gets no byte code and hence it flags some errors.
UNDERSTANDING CLASSPATH:
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath.
The CLASSPATH is an environment variable that tells the Java compiler where to look for
class files to import.
If our package exists in e:\sub then we need to set class path as follows:
We are setting the classpath to e:\sub directory and current directory (.) an
%CLASSPATH% means retain the already available classpath as it is.
Creating Sub package in a package: We can create sub package in a package in the format:
package packagename.subpackagename;
e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use
the classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.
ACCESSING A PACKAGES:
Access Specifier: Specifies the scope of the data members, class and methods.
private members of the class are available with in the class only. The scope of
private members of the class is ―CLASS SCOPE‖.
public members of the class are available anywhere . The scope of public members of
the class is "GLOBAL SCOPE".
default members of the class are available with in the class, outside the class and in its
sub class of same package. It is not available outside the package. So the scope
of default members of the class is "PACKAGE SCOPE".
protected members of the class are available with in the class, outside the class and in its
sub class of same package and also available to subclasses in different package also.
int d = 4;
}
Classes Interfaces
Classes have instances as variables and Interfaces have instances as abstract methods
methods with body and final constants variables.
Inheritance goes with extends keyword Inheritance goes with implements keywords.
The variables can have any acess specifier. The Variables should be public, static, final
Multiple inheritance is not possible It is possible
Classes are created by putting the keyword Interfaces are created by putting the keyword
class prior to classname. interface prior to interfacename(super class).
SKCW | DEPARTMENT OF COMPUTER APPLICATIONS
PROGRAMMING IN JAVA | UNIT - III
Classes contain any type of methods. Classes Interfaces contain mustly abstract methods.
may or may not provide the abstractions. Interfaces are exhibit the fully abstractions
A programmer uses an abstract class when there are some common features shared by all
the objects. A programmer writes an interface when all the features have different
implementations for different objects. Interfaces are written when the programmer wants
to leave the implementation to third party vendors. An interface is a specification of method
prototypes. All the methods in an interface are abstract methods.
An interface is a specification of method prototypes.
An interface contains zero or more abstract methods.
All the methods of interface are public, abstract by default.
An interface may contain variables which are by default public static final.
Once an interface is written any third party vendor can implement it.
All the methods of the interface should be implemented in its implementation classes.
If any one of the method is not implemented, then that implementation class
should be declared as abstract.
We cannot create an object to an interface.
We can create a reference variable to an interface.
An interface cannot implement another interface.
An interface can extend another interface.
A class can implement multiple interfaces.
An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface. The general form of a class that includes the implements clause
looks like this:
If a class implements more than one interface, the interfaces are separated with a comma. If a
class implements two interfaces that declare the same method, then the same method will be used
by clients of either interface. The methods that implement an interface must be declared public.
Also, the type signature of the implementing method must match exactly the type signature
specified in the interface definition.
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract. For example:
abstract class Incomplete implements Callback {
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Here, the class Incomplete does not implement callback( ) and must be declared as abstract.
Any class that inherits Incomplete must implement callback( ) or be declared abstract itself.
Nested Interfaces
An interface can be declared a member of a class or another interface. Such an interface is
called a member interface or a nested interface. Anested interface can be declared as public,
private, or protected. This differs from a top-level interface, which must either be declared
as public or use the default access level, as previously described. When a nested interface is
used outside of its enclosing scope, it must be qualified by the name of the class or interface
of which it is a member. Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified.
Here is an example that demonstrates a nested interface:
// A nested interface example.
// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
Notice that the name is fully qualified by the enclosing class‟ name. Inside the main( ) method,
an A.NestedIF reference called nif is created, and it is assigned a reference to a B object.
Because B implements A.NestedIF, this is legal.
}
class Rectangle implements Shape
{ double l,b;
Rectangle (double length, double breadth)
{ l = length;
b = breadth;
}
public void area ()
{ System.out.println ("Area of a Rectangle is : " + l*b );
}
APPLYING INTERFACE:
To understand the power of interfaces, let‟s look at a more practical example. In earlier chapters,
you developed a class called Stack that implemented a simple fixed-size stack. However, there
are many ways to implement a stack. For example, the stack can be of a fixed size or it can be
―growable.‖ The stack can also be held in an array, a linked list, a binary tree, and so on. No
matter how the stack is implemented, the interface to the stack remains the same. That is, the
methods push( ) and pop( ) define the interface to the stack independently of the details of the
implementation. Because the interface to a stack is separate from its implementation, it is easy to
define a stack interface, leaving it to each implementation to define the specifics. Let‟s look at
two examples.
First, here is the interface that defines an integer stack. Put this in a file called IntStack.java.
VARIABLES IN INTERFACES:
You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When you include that
interface in a class (that is, when you ―implement‖ the interface), all of those variable names will
be in scope as constants. (This is similar to using a header file in C/C++ to create a large number
of #defined constants or const declarations.) If an interface contains no methods, then any class
that includes such an interface doesn‟t actually implement anything.
It is as if that class were importing the constant fields into the class name space as final
variables. The next example uses this technique to implement an automated ―decision maker‖:
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Notice that this program makes use of one of Java‟s standard classes: Random. This class
provides pseudorandom numbers. It contains several methods that allow you to obtain random
numbers in the form required by your program. In this example, the method nextDouble( ) is
used. It returns random numbers in the range 0.0 to 1.0.
In this sample program, the two classes, Question and AskMe, both implement the
SharedConstants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined.
Inside each class, the code refers to these constants as if each class had defined or inherited them
directly. Here is the output of a sample run of this program. Note that the results are different
each time it is run.
Later
Soon
No
Yes
EXTENDING INTERFACES:
One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes. When a class implements an interface that inherits another interface,
it must provide implementations for all methods defined within the interface inheritance
chain. Following is an example:
// One interface can extend one or more interfaces..
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
}
}
As an experiment, you might want to try removing the implementation for meth1( ) in MyClass.
This will cause a compile-time error. As stated earlier, any class that implements an interface
must implement all methods defined by that interface, including any that are inherited from other
interfaces.
Although the examples we‟ve included in this book do not make frequent use of packages or
interfaces, both of these tools are an important part of the Java programming environment.
Virtually all real programs that you write in Java will be contained within packages. A number
will probably implement interfaces as well. It is important, therefore, that you be comfortable
with their usage.
Multithreaded Programming:
Multi-threading means multiple flow of control. Multi-threading programming is a
conceptual paradigm for programming where one can divide a program into two or more
processes which can be run in parallel. There are two main advantages of multi-threading : Fist,
program with multiple threads will, in general, result in better utilization of system resources,
including the CPU, because another line of execution can grab the CPU when one line of
execution is blocked. Second, there are several problems better solved by multiple threads. For
example, we can easily write a multi-threaded program to show animation, play music, display
documents, and down load files from the network at the same time.
Java is a multi-threaded language. Java allows to write a program where more than one
processes can be executed concurrently within the single program. Java's threads are often
referred to as light weight threads, which means that they run in the same memory space.
Because Java threads run in the same memory space, they can easily communicate among
themselves because an object in one thread can call a method in another thread without any
overhead from the operating system. In this Tutorial we will learn how to do multi-threaded
programming in Java.
/* Creating three threads using the class Thread and then running them concurrently.
*/
class ThreadA extends Thread{
public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("From Thread A with i = "+ -1*i);
}
System.out.println("Exiting from Thread A ...");
}
}
OUTPUT:
From Thread A with i = -1
From Thread A with i = -2
From Thread A with i = -3
From Thread B with j= 2
From Thread A with i = -4
From Thread A with i = -5
Exiting from Thread A ...
... Multithreading is over
From Thread C with k = 1
From Thread B with j= 4
From Thread B with j= 6
From Thread B with j= 8
From Thread B with j= 10
Exiting from Thread B ...
From Thread C with k = 3
From Thread C with k = 5
From Thread C with k = 7
From Thread C with k = 9
Exiting from Thread C ...
When we will create a new thread, actually a new object will be instantiated from this
Runnable interface as the target of our thread, meaning that the thread will look for the code for
the run( ) method within our object's class instead of inside the Thread's class.
* Creating three threads using the Runnable interface and then running them concurren
tly. */
class ThreadX implements Runnable{
public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("Thread X with i = "+ -1*i);
}
System.out.println("Exiting Thread X ...");
}
}
t1.start();
t2.start();
t3.start();
OUTPUT:
Thread X with i = -1
Thread X with i = -2
Thread Z with k = 1
Thread Z with k = 3
Thread Z with k = 5
Thread Z with k = 7
Thread Z with k = 9
Exiting Thread Z ...
... Multithreading is over
Thread Y with j = 2
Thread Y with j = 4
Thread Y with j = 6
Thread Y with j = 8
Thread Y with j = 10
Exiting Thread Y ...
Thread X with i = -3
Thread X with i = -4
Thread X with i = -5
Exiting Thread X ...
Threads move from one state to another via a variety of means. The common methods for
controlling a thread's state is shown in Figure. Below, we are to summarize these methods :
start ( ) : A newborn thread with this method enter into Runnable state and Java run time create
a system thread context and starts it running. This method for a thread object can be called once
only
stop( ) : This method causes a thread to stop immediately. This is often an abrupt way to end a
thread.
suspend( ) : This method is different from stop( ) method. It takes the thread and causes it to stop
Other methods like wait(), notify(), join() etc. will be discussed in subsequent
discussion.
/* Use of yield(), stop() and sleep() methods */
OUTPUT:
Start Thread A ....
Start Thread C ....
Start Thread B ....
... End of executuion
From Thread A: i = 1
From Thread B: j = 1
From Thread B: j = 2
From Thread B: j = 1
From Thread A: i = 2
From Thread A: i = 3
From Thread A: i = 4
From Thread A: i = 5
... Exit Thread A
From Thread B: j = 2
From Thread B: j = 3
From Thread B: j = 4
From Thread B: j = 5
... Exit Thread C
try{
System.out.println ( "Second thread starts running");
System.out.println ( "Second thread is suspended itself ");
suspend( );
System.out.println (" Second thread runs again" );
}
catch(Exception e){ }
}
}
class Demonstration_116{
public static void main (String args[ ] ){
try{
Thread1 first = new Thread1( ); // It is a newborn thread i.e. in N
ewborn state
Thread2 second= new Thread2( ); // another new born thread
OUTPUT:
Revive the second thread
First thread starts running
Second thread starts running
Second thread is suspended itself
Second thread went for 10 seconds sleep
Thread Methods:
Following is the list of important methods available in the Thread class.
The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the
currently running thread.
Thread Priorities :
public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
// Default 5
System.out.println("t1 thread priority : "
+ t1.getPriority());
// Default 5
System.out.println("t2 thread priority : "
+ t2.getPriority());
// Default 5
System.out.println("t3 thread priority : "
+ t3.getPriority());
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// 2
System.out.println("t1 thread priority : "
+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "
+ t2.getPriority());
// 8
// Main thread
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
Output
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Synchronization:
In Java, the threads are executed separately to each other. These types of threads are called as
asynchronous threads. But there are two problems may be occurs with asynchronous threads.
Two or more threads share the similar resource (variable or method) while only one of them can
access the resource at one time.
If the producer and the consumer are sharing the same kind of data in a program then either producer
may make the data faster or consumer may retrieve an order of data and process it without its existing.
Suppose, we have created two methods as increment( ) and decrement( ). which increases or
decreases value of the variable "count" by 1 respectively shown as:
When the two threads are executed to access these methods (one for increment( ),another for
decrement( )) then both will distribute the variable "count". in that case, we can't be sure thatwhat
value will be returned of variable "count".
We can see this problem in the diagram shown below:
Start
Thread 1 Thread 2
Shared
Variable or method
To avoid this problem, Java uses monitor also known as ―semaphore‖ to prevent data from
being corrupted by multiple threads by a keyword synchronized to coordinate them and
intercommunicate to each other. It is basically a mechanism which allows two or more threads to
share all the available resources in a sequential manner. Java's synchronized is used to ensure
that only one thread is in a critical region. Critical region is a lock area where only one thread is
run (or lock) at a time. Once the thread is in its critical section, no other thread can enter to that
critical region. In that case, another thread will has to wait until the current thread leaves its
critical section.
Lock:
Lock term refers to the access approved to a particular thread that can access the shared
resources. At any given time, only one thread can hold the lock and thereby have access to the
shared resource. Every object in Java has build-in lock that only comes in action when the object
has synchronized method code. By associating a shared resource with a Java object and its lock,
the object can act as a guard, ensuring synchronized access to the resource. Only one thread at a
time can access the shared resource guarded by the object lock.
Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire
the lock until the lock is not released by first thread. Acquire the lock means the thread currently
in synchronized method and released the lock means exits the synchronized method.
Remember the following points related to lock and synchronization:
Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
All methods in a class need not to be coordinated. A class can have both synchronized and non-
synchronized methods.
If two threads wants to execute a synchronized method in a class, and both threads are using the
similar instance of the class to invoke the method then only one thread can execute the method at a
time.
If a class has both synchronized and non-synchronized methods, multiple threads can still access
the class's non-synchronized methods. If you have methods that don't access the data you're trying to
protect, then you don't need to synchronize them. Synchronization can cause a hit in several cases (or
even deadlock if used incorrectly), so you should be careful not to overuse it.
If a thread goes to sleep, it holds any locks it has—it doesn't let go them.
A thread can obtain more than one lock. For example, a thread can enter a synchronized method,
thus acquiring a lock, and then directly invoke a synchronized method on a different object, thus
acquiring that lock as well. As the stack unwinds, locks are unrestricted again.
Synchronized Methods:
Any method is specified with the keyword synchronized is only executed by one thread at
a time. If any thread wants to implement the synchronized method, firstly it has to obtain the
objects lock. If the lock is already held by another thread, then calling thread has to wait.
Synchronized methods are useful in those situations where methods are executed concurrently,
so that these can be intercommunicate control the state of an object in ways that can corrupt the
state if . Stack implementations usually define the two operations push and pop of elements as
synchronized, that‗s why pushing and popping are mutually exclusive process. For Example - if
several threads were sharing a stack, if one thread is popping the element on the stack then
another thread would not be able to pushing the element on the stack.