Unit Iii
Unit Iii
packages :
package : A package is a group of similar types of classes, interfaces and sub-
packages. A package is a directory for holding java files. A package can be defined
as a collection used for grouping a variety of classes and interfaces based on their
functionality.
1. built-in packages
2. user-defined package.
Built-in packages :
java has many predefined packages which can be used in programs and are
given by sun micro systems. Some of them are java, lang, awt, javax, swing, net,
io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
10. obj.msg();
11. }
12. }
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to impo
you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
If you import a package, all the classes and interface of that package will be imported excluding the classes and interfa
subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Ex 2 :
package mypack;
class Addition
{
void sum(int a,int b)
{
System.out.println(“ sum = “ + (a+b));
}
}
save : Addition.java
compile: javac -d . Addition.java
----------------------------------
package mypack;
class Subtraction
{
void diff(int a,int b)
{
System.out.println(“Difference =” + (a-b));
}
}
save : Subtraction.java
compile : javac -d . Subtraction.java
-------------------------
package mypack;
import mypack.*;
class PackDemo
{
public static void main(String args[])
{
Addition a = new Addition();
Subtraction b = new Subtraction();
a.sum(10,20);
b.diff(10,20);
}
}
save : PackDemo.java
Compile : javac -d . PackDemo.java
Execute : java mypack.PackDemo
in the above programs , Addition and Subtraction ,PackDemo classes are placed in the package
called mypack. Any class can import the classes of the same package or from the other
packages.Here, PackDemo class is importing the classes from mypack. compile all the three
programs using the above commands and we can execute PackDemo class which is in mypack
package with the statement
“java mypack.PackDemo” or move to mypack directory and execute using the statement “ java
PackDemo” or you can set the CLASSPATH and then execute your program.
Setting the classpath:
if the class files are not in the current directory, we need to set the classpath.
Whenever, we execute / compile any class files, JDK tools javac and java , search the package /
class file in the user classpath which is the current directory by default. If the classes are not in
the current directory, then we need to set the classpath.
The classpath can be set in two ways :
1. It is an environment variable which can be set using the system utility in the control
panel or at the DOS prompt as shown:
set CLASSPATH = %CLASSPATH% ; d:\mypack;
%classpath% is used to keep the existing path intact and append our new path to it.
To make the changes permanent, edit the environment variable in the control panel
right click on
computer-> properties -> Advanced System Setting -> Engironment
variables -> classpath
2. To use user defined packages, we can use –classpath option
Ex : javac –cp “d:\mypack” PackDemo.java
Sub Packages :
sub packages can be designed in hierarchy i.e one package can be a part of another
package. This can be achieved by specifying multiple names of packages at various levels of
hierarchy separated by dots.
syntax :
package rootpackagename.subpackagename;
using packages :
To import all the classes in a package, we can use wildcard notation.
import java.awt.*;
to import a specific class we can specify the classname as
import java.awt.Rectangle;
classes in a package java.lang are automatically imported . For all other classes , you must
supply an import statement.
Example :
Recursive program to calculate factorial in a package.
package p1;
public class RecFactorial
{
public long fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n-1));
}
}
save : RecFactorial.java
compile : javac -d . RecFactorial.java
-------------------------------------------
package p2;
import p1.*;
class Test
{
public static void main(String args[])
{
RecFactorial obj = new RecFactorial();
System.out.println("factorial = " +obj.fact(5));
}
}
save : Test.java
compile :javac -d . Test.java
execute : java p2.Test
Access Specifiers :
We can use access specifier before a class or its members. There are 4
access specifiers available in java.
Access within class within package outside package by subclass outside package
Modifier only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1.private :
The private access modifier is accessible only within the class.
In this example, we have created two classes A and PrivateEx. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.
class A
{
private int x;
private void display()
{
System.out.println("hello");
}
}
class PrivateEx
{
public static void main(String args[])
{
A obj = new A();
obj.x=10; // compile error, private variable can not be accessed outside the class
obj.display(); //compile error, private method cannot be accessed outside the class
}
}
Note:
If you make any class constructor as private, you cannot create the instance of that class from outside
the class.
2.Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
3.Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
1. /save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Exception Handling
Exception :
For ex:
1. Division by zero(ArithmeticException)
2. Accessing a file which is not present(FileNotFoundException)
3. failure of I/O operation(IOException)
4. Illegal use of null(NullPointerException)
5. Trying to access 6th element of array when it has 5 elements only
(ArrayIndexOutOfBoundsException)
There are predefined classes(mentioned in the parenthesis above) for all exception types
representing each situation. The topmost class in the hierarchy is java.lang.Throwable
Types of Exceptions:
1. checked exceptions
2. unchecked exceptions
3. error
1.checked exceptions:
the exceptions that are checked at compilation time by the javacompilerare called
“checked exceptions” . These are exceptional conditions that are internal to the application that
could be anticipated and recovered.
The exceptions that are checked by the JVM at runtime are known as unchecked
exceptions. These are exceptional conditions that are internal to the application and the
application usually cannot anticipate or recover from.
3.Error :
These are exceptional conditions that are external to the application and that the
application usually cannot anticipate or recover from.
suppose that an application successfully opens a file for input but is unable to read the
file because of a hardware or software mall functioning. In this case it throws java.io.IOError
1.try
2.catch
3.throw
4.throws
5.finally
try ..catch:
the try/catch block can be placed within any method that you feel can throw exceptions.
All the statements to be tried for exceptions are put in a try block and immediately following
the try is the catch block.
catch block:
it is used to catch any exception raised from the try block. If exception rises in any
statements, then the following statements of that try block are not executed and control passes
to corresponding catch block.
finally :
The "finally" block is used to execute the important code of the program. It is executed whether
an exception is handled or not.
throw:
The "throw" keyword is used to throw an exception.
throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.
Ex :
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
Exception handling:
when there is an exception, the user data may be corrupted . This should be tackled by
java programmer by carefully designing the program. For this, he should perform the following
3 steps.
step1 :
The programmer should observe the statements in his program where there may be a
possibility of exceptions. such statements should be written inside a try block.
A try block looks like as follows
try
{
statements;
}
The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. when JVM understands that there is an exception, it stores the exception
details in an exception stack and then jumps into a catch block.
step2 :
The programmer should write the catch block where he should display the exception
details to the user. This helps the user to understand that there is some error in the program.
The programmer should also display a message regarding what can be done to avoid this error.
catch block looks as follows:
catch(Exceptionclass ref)
{
statements;
-------
--------
}
step3 :
The programmer should perform clean up operations like closing the files and
terminating the threads. The programmer should write this code in the finally block.
finally block look like:
finally
{
// statements;
}
The specialty of finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not.
performing the above three tasks is called exception handling.
try
{
----
----
}
catch(Throwable e)
{
---
---
}
finally
{
-----
-----
}
Ex : write java program which shows the use of try, catch and finally block.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
int n=25/0;
System.out.println(n);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Multiple catch clauses or Handling Multiple Exceptions:
most of the times there is possibility of more than one exceptionprsent in the program.
In this case, the programmer should write multiple catch blocks to handle each one of them.
Syntax :
try
{
statements
}
catch(ExceptionType1 e)
{
}
catch(ExceptionType2 e)
{
}
Ex : Write a program which shows how to handle the ArithmeticException and
ArrayIndexOutofBoundsException
class ExceptionTest
{
public static void main(String args[])
{
int b[]={10,20,30,40,50};
try
{
int a=5/0;
System.out.println(a);
System.out.println(b[5]);
}
catch(ArithmeticException e)
{
System.out.println("divide by zero error");
}
catch(ArrayIndexOutofBoundsException e)
{
System.out.println(“please see that array index is within the range”);
}
}
throw clause :
there is also a throw statement available in java to throw an exception explicitly and
catch it.It is used to throw our own exception.
Ex:
class ExceptionTest
{
public static void main(String args[])
{
int a=10, b=0,c;
try
{
if(b==0)
throw new ArithmeticException(“divisor is zero”);
else
{
c=a/b;
System.out.println(c);
}
}
catch(ArithmeticException e)
{
System.out.println(“Exception handled “ + e);
}
}
}
Ex:
class ExceptionTest3
{
static void fun() throws ArithmeticException
{
int a=12;
System.out.println(a/0);
}
try
{
fun();
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block executed");
}
}
}
user-defined exceptions:
sometimes, the built – in exceptions in java are not able to describe a certain situation. In
such cases, the user can create his own exceptions which are called user-defined exceptions.
1. the user should create an exception class as a subclass to exception class. Since all
exceptions are subclasses of exception class, the user should also make his class a
subclass to it.
this is done as
class MyException extends Exception
2. The user can write a default constructor in his own exception class. He can use it, in case
he does not want to store any exception details. If the user does not want to create an
empty object to his exception class, he can eliminate writing the default constructor.
MyException()
{
}
3. The user can create a parameterized constructor with a string as a parameter. He can
use this to store exception details. He can call super class(Exception) Consturctions from
this and send the string there.
MyException(String s)
{
super(s);
}
4. when the user wants to raise his own exception, he should create an object to his
exception class and throw it using throw clause as.
MyException m=new MyException(“Exception details”);
throw m;
Ex:
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class ExceptionTest4
{
Assertions :
Assertions are Boolean expressions that are used to test/validate the code. They are basically
used during testing and development phases. They are added in java 1.4 to creat reliable
programs that are correct and robust.
Ex:
conditions such as a number is positive or negative , array / reference is null or
notcan be checked by asserting them.
Assertions in java are declared with the help of assert keyword as
assert expression1; // assert x>0;
or
assert expression1 : expression2 // assert x<0: “value ok”;
Assertions have to be enabled explicitly ; they are disabled by default. Using the –ea and
–da options of java, we can enable and disable assertions.
-ea enable assertions
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Multitasking
• Each process has an address in memory. In other words, each process allocates a separate
memory area.
• A process is heavyweight.
• Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
• A thread is lightweight.
Thread in java
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
There can be multiple processes inside the OS, and one process can have multiple threads.
Thread class provides constructors and methods to create and perform operations on a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
12) static void yield() It causes the currently executing thread object to
pause and allow other threads to execute
temporarily.
16) void destroy() It is used to destroy the thread group and all of its
subgroups.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static boolean interrupted() It tests whether the current thread has been
interrupted.
22) static int activeCount() It returns the number of active threads in the
current thread's thread group.
24) static boolean holdLock() It returns true if and only if the current thread holds
the monitor lock on the specified object.
25) static void dumpStack() It is used to print a stack trace of the current thread
to the standard error stream.
27) static int enumerate() It is used to copy every active thread's thread group
and its subgroup into the specified array.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this
thread belongs
33) void setContextClassLoader() It sets the context ClassLoader for the Thread.
34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the thread.
35) static getDefaultUncaughtExcepti It returns the default handler invoked when a thread
Thread.UncaughtExceptionHan onHandler() abruptly terminates due to an uncaught exception.
dler
36) static void setDefaultUncaughtExcepti It sets the default handler invoked when a thread
onHandler() abruptly terminates due to an uncaught exception.
1)New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Runnable interface:
• The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread.
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Ex : write a program to create a new thread by extending Thread class
class MyThread extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
MyThread t = new MyThread();
t.start();
}
}
new threads can be created by creating a class that implements the Runnable
interface.
Steps to be followed for thread creation are :
}
2. after implementing Runnable interface , the class need to implement the run()
method, which is of form
public void run()
{
}
the code that thread will execute is placed insidethe run() method.
String s;
int time;
MultiThreadR(String s, int t)
{
this.s = s;
time = t;
Thread t1= new Thread(this);
t1.start();
}
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(s);
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
public static void main(String args[])
{
new MultiThreadR("Thread1",1000);
new MultiThreadR("Thread2",2000);
new MultiThreadR("Thread3",3000);
}
}
Thread Synchrnization:
There can be instances when two or more threads access a common resource, say a common
data or file. In order to maintain consistency, it becomes important that the resource is made available
to only one thread at a time.
Ex : If there are two threads, one responsible for writing to a file and other for reading from the same
file. If both the threads start concurrentlye , both would try to access the file at the same time.
Obsivously , if the first thread has not written the values completely, the values read by the second
thread would be inconsistent.
Java has such in built mechanism, which lets only one thread use a resource at a time known as
synchronization. To do this, we have the concept of monitors here. Monitor is an object that is used as a
mutually exclusive lock on the resource to be accessed.
A monitor can be owned by only one thread at a time. A thread enters the monitor as soon as it acquires
the lock. All the other threads cannot enter the locked monitor, unless it is unlocked or the first thread
exits the monitor. During this period, other threads are waiting for the lock on the monitor. If a thread
exits the monitor , it can again enter the same monitor at some later stage.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
• Mutual Exclusive
– Synchronized method.
– Synchronized block.
}
}
Now, if n number of threads want to use the method(), the system will not allow them to do so. the
highest priority thread will lock the monitor for the method making it inaccessible to other threads.
Once the thread locking for the monitor finishes its job , it releases the monitor for the use of other
waiting threads.
2) synchronized statements:
There are two methods suspend() and resume() used for suspending an executing
thread temporarily and resuming the suspension, respectively.
suspend():
this method puts a thread in suspended state and can be resumed using
resume() method.
resume():
This method resumes a thread which was suspended using suspend() method.
class Table
{
synchronized void printable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n + “ * “ + i + “=” + (n*i));
try
{
Thread.sleep(400);
}
catch(InterruptedException e)
{
System.out.println€;
}
}
}
}
class MyThread1 exabtends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class Table
{
void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n + "* " + i + "="+ (n*i));
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
synchronized(t)
{
t.printTable(5);
}
}
}
o wait()
o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
public final void wait(long timeout)throws InterruptedException waits for the specified amount
of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax: