Unit Ii
Unit Ii
***************************************************************************
Packages
***************************************************************************
Definition
A package is a group of related classes and interfaces. The grouping is usually done
according to functionality. In fact, packages act as “containers” for classes.
Java classes can be grouped together in packages. A package name is the same as the
directory (folder) name which contains the .java files.
Benefits of using packages
The classes contained in the packages of another program can be easily reused.
Packages also allow programmers to separate design from coding.
In packages, classes can be declared uniquely compared with classes in other packages.
Java Packages provide a way to ‘hide’ classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
Packages provide access protection.
Java package removes naming collision.
Different types of Packages
Java packages are classified into two types. They are:
1. Java API Packages
2. User Defined Packages
Java API Packages
Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time we use the packages available with the Java API as shown
in Figure 10.1.
Figure 10.1: Frequently used API packages
class Palintest
{
public static void main(String args[]) throws IOException
{
Palindrome P=new Palindrome();
Scanner in=new Scanner(System.in);
String message;
System.out.println("\tJava Program using Package");
System.out.println("\t***********************");
System.out.println("Input");
System.out.println("-------");
System.out.println("Enter the String");
String str= in.nextLine();
message=P.test(str);
System.out.println("Output");
System.out.println("---------");
System.out.println("The given string is "+message);
}
}
C:\>md mypackage
C:\>cd mypackage
C:\mypackage>path="c:\program files\java\jdk1.6.0_01\bin";
C:\mypackage>javac Palindrome.java
C:\mypackage>cd\
C:\>path="c:\program files\java\jdk1.6.0_01\bin";
C:\>javac Palintest.java
C:\>java Palintest
Output
---------
The given string is Palindrome
C:\>java Palintest
Java Program using Package
***********************
Input
-------
Enter the String
welcome
Output
---------
The given string is Not Palindrome
C:\>
9.6 Access Protection
Java provides many levels of security that provides the visibility of members (variables
and methods) within the classes, subclasses, and packages.
There are four types of access modifiers available in java:
1) Default – No keyword required
2) Private
3) Protected
4) Public
1) Default
When no access modifier is specified for a class, method, or data member – It is said to
be having the default access modifier by default.
The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.
2) private
The private access modifier is specified using the keyword private.
The scope of private modifier is limited to the class only.
The methods or data members declared as private are accessible only within the
class in which they are declared.
3) protected
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
4) public
The public access modifier is specified using the keyword public.
The members, methods and classes that are declared public can
be accessed from anywhere.
There is no restriction on the scope of public data members.
9.7 Accessing a Package
The import statement
The import statement is used to access the package.
The general form of import statement for searching a class is:
import package1 [.package2] [.package3].classname;
Here, package1 is the name of the top-level package. package2 is the name of the
package that is inside the 1st package i.e. package1 and so on. Programmers can use any
number of packages in the package hierarchy. At the end, the explicitly classname is
specified.
The import statement should appear before any class definitions in a source file.
Multiple import statements are allowed. The following is an example of importing a
particular class:
import firstPackage.secondPackage.MyClass;
After defining this statement, all members of the class MyClass can be directly accesses
using the class name or its objects directly without using the package name.
We can also use another approach as follows:
import packagename.*;
Here, packagename may denote a single package or hierarchy of packages. The star (*)
indicates that the compiler should search this entire package hierarchy where it
encounters a class name. this implies that we can access all classes contained in the
above package directly.
**************************************************************************
Interfaces
***************************************************************************
****
10.1 Introduction
An interface is similar to a class, but it contains abstract methods and static final
variables only.
To access the interface methods, the interface must be "implemented" by another class
with the implements keyword.
Like abstract classes, interfaces cannot be used to create objects.
Interface methods do not have a body - the body is provided by the "implement" class.
On implementation of an interface, we must override all of its methods.
Interface methods are by default abstract and public..
Interface attributes are by default public, static and final.
An interface cannot contain a constructor.
10.2 Defining an Interface
The syntax for defining an interface is very similar to that for defining a class.
The general form of an interface definition is:
interface InterfaceName
{
//Variable declaration;
//Methods declaration;
}
Here, interface is the keyword and InterfaceName is any valid Java variable. Variables
are declared as follows:
static final type VariableName=value;
All variables are declared as constants. Methods declaration will contain only a list of
methods without any body statements. Methods are declared as follows:
return-type methodName(parameter_list);
Example 1:
interface Item
{
static final float code=1001;
static final String name=”Fan”;
void display();
}
Here, the code for the method is not included in the interface and the method declaration
simply ends with a semicolon. The class that implements this interface must define the code
for the method.
Example 2:
interface Area
{
float static float pi=3,142F;
float compute(float x, float y);
void show();
}
Example:
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
display();
}
The interface Item would inherit both the constants code and name into it. The variables
name and code are declared like simple variables. It is allowed because all the variables
in an interface are created as constants although the keywords final and static are not
present.
We can also combine several interfaces together into a single interface. Following
declarations are valid.
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface ItemMethods
{
display();
}
While interfaces are allowed to extend to other interfaces, subinterfaces cannot define
the methods declared in the superinterfaces, Instead, it is the responsibility of any class
that implements the derived interface to define all the methods.
An interface cannot extend classes.
10.4 Implementing Interfaces
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.
Interfaces are used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface. This is done as
follows:
class classname implements Interfacename
{
//Body of classname
}
Here the class classname “implements” the interface interfacename. A more general form
of implementation may look like this:
class classname extends superclass implements Interfac1, Interface2, …
{
//Body of classname
}
This shows that a class can extend another class while implementing interfaces. When a
class implements more than one interface, they are separated by a comma.
Example:
***************************************************************************
Exception Handling
***************************************************************************
11.1 Introduction
Exception Handling is a construct in some programming languages to handle or
deal with errors automatically.
Errors are the wrongs that can make a program go wrong. An error may produce an
incorrect output or may terminate the execution of the program abruptly or even may
cause the system to crash.
11.2 Types of Errors
Errors may be broadly classified into two categories:
Compile-time errors
Run-time errors
Compile-Time Errors
A compile-time error is an error that is detected by the compiler. Compile-time errors
occur while a program is being compiled.
All syntax errors will be detected and displayed by the Java compiler and therefore these
errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file. It is therefore
necessary that we fix all the errors before we can successfully compile and run the
program.
Example:
Most of the compile-time errors are due to typing mistakes. Typographical errors are hard
to find. The most common problems are:
Missing semicolon
Missing brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables
Incompatible types in assignments / initialization
Use of = in place of == operator
Run-Time Errors
An error that occurs during the execution of a program is called a run-time error.
For example, running out of memory will often cause run-time error.
Most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Trying to store a value into an array of an incompatible class or type
Trying to cast an instance of a class to one of its subclasses
Passing a parameter that is not in a valid range or value for a method
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference as a legitimate object reference to access a method or a
variable
Converting invalid string to a number
Accessing a character that is out of bounds of a string
Example:
The above program is syntactically correct and therefore does not cause any problem during
compilation. However, while executing, it displays the following message and stops without
executing further statements.
Java.lang.ArithmeticException: / by zero
At Error2.main(Error2.java:10)
When Java run-time tries to execute a division by zero, it generates an error condition, which
causes the program to stop after displaying an appropriate message.
11.3 Exceptions
The error handling code basically consists of two segments, one to detect errors and to
throw exceptions and the other to catch exceptions and to take appropriate actions.
All exception classes are subtypes of the java.lang.Exception class. The Exception class is
a subclass of the Throwable class.
11.4 Types of Exception in Java
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
1. ArithmeticException
It is thrown when a class does not contain the field (or variable)
specified
8. NoSuchMethodException
The try block can have one or more statements that could generate an exception. If any
statement generates an exception, the remaining statements in the block are skipped and
execution jumps to the catch block that is placed next to the try block.
The catch block can have one or more statements that are necessary to process the
exception.
Every try statement should be followed by at least one catch statement; otherwise
compiler error will occur.
Example:
//Java program to demonstrate try…catch Statement
import java.io.*;
class TryCatch_Ex
{
public static void main(String args[])
{
int num1, num2;
try
{
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
}
catch (ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
}
}
Output:
You should not divide a number by zero
11.6 Multiple catch Statements
A single try block can have multiple catch blocks.
Each catch block must contain a different exception handler.
Syntax:
try
{
//Statements that may cause an exxception
}
catch(ExceptionType1 e1)
{
//Statements
}
catch(ExceptionType2 e2)
{
//Statements
}
catch(ExceptionType3 e3)
{
//Staatements
}
...
catch(ExceptionTypeN en)
{
//Statements
}
Example:
//Java program using multiple catch blocks
import java.util.Scanner;
public class MultiCatchEx
{
public static void main(String[] args)
{
int x, y;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter the first number");
x = Integer.parseInt(sc.nextLine());
System.out.println("Enter the second number");
y = Integer.parseInt(sc.nextLine());
int z = x / y;
System.out.println("z = " +z);
}
catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by 0");
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid data types are entered, number must be an integer.");
}
}
}
Output:
Enter the first number
40
Enter the second number
20
z=2
--------------------------------------------
Enter the first number
40
Enter the second number
0
A number cannot be divided by 0
--------------------------------------------
Enter the first number
40
Enter the second number
5.5
Invalid data types are entered, number must be an integer.
11.7 Nested try Statements
A try block within another try block is known as nested try block.
The try block which encloses another try block is called outer try block and the enclosed
try block is called inner try block.
Syntax:
Output:
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Example:
Output:
java.io.IOException: IOException occurred
The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable.
Thus, all exceptions, including those that we create, have the methods defined by
Throwable available to them.
Methods Defined by Throwable
Sl. No. Method Description
Example:
****************************************************************************
Multithreading
***************************************************************************
***
12.1 Definition
This method tests whether the current thread has been interrupted.
Syntax:
public static boolean interrupted()
12. isAlive()
This method tests if the thread is alive.
Syntax:
public final boolean isAlive()
13. isInterrupted()
This method tests whether the thread has been interrupted.
Syntax:
public boolean isInterrupted()
14. join()
This method waits for a thread to die.
Syntax:
public final void join() throws InterruptedException
1. join(long millis)
This method waits at most millis milliseconds for a thread to die.
Syntax:
public final void join(long millis) throws InterruptedException
Parameters:
millis - the time to wait in milliseconds
16. resume()
This method is used to resume the suspended thread.
public void resume()
17. run()
This method is used to perform action for a thread.
Syntax:
public void run()
18. start()
This method causes the thread to begin execution; the Java Virtual Machine calls the
run method of the thread.
Syntax:
public void start()
19. sleep(long millis)
This method causes the currently executing thread to sleep (temporarily cease execution)
for the specified number of milliseconds.
Syntax:
public static void sleep(long millis) throws InterruptedException
Parameters:
millis - the length of time to sleep in milliseconds
20. setPriority(int newPriority)
This method changes the priority of the thread.
Syntax:
public final void setPriority(int newPriority)
Parameters:
newPriority - priority to set this thread to
21. setName(String name)
This method changes the name of the thread.
Syntax:
public final void setName(String name)
Parameters:
name - the new name for this thread.
22. stop()
This method is used to stop the thread.
Syntax:
public void stop()
23. suspend()
This method is used to suspend the thread.
Syntax:
public void suspend()
24. toString()
This method returns a string representation of the thread, including the thread’s name,
priority, and thread group.
Syntax:
public String toString()
25. yield()
This method causes the currently executing thread object to temporarily pause and allow
other threads to execute.
Syntax:
public static void yield()
12.5 Creating a Thread
There are two ways to create a thread:
i) Extending the Thread class
ii) Implementing the Runnable interface
i) Extending the Thread class
The first way to create a thread is to create a new class that extends Thread class using
the following steps.
1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start() method to initiate the thread execution.
Declaring the Class
The Thread class can be extended as follows:
The run() method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic
implementation of run() will look like this:
public void run()
{
……………….
………………. // Thread code here
……………….
}
When we start the new thread, Java calls the thread’s run() method, so it is the run() where
all of the action takes place.
Example:
// Java program to implement the Runnable interface
import java.io.*;
class Multi implements Runnable
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi m1=new Multi();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:
Thread is running...
12.6 Starting New Thread
The start() method of thread class is used to begin the execution of thread. The result of
this method is two threads that are running concurrently: the current thread (which
returns from the call to the start method) and the other thread (which executes its run
method).
The start thread performs the following tasks:
It stats a new thread
The thread moves from New State to Runnable state.
When the thread gets a chance to execute, its target run() method will run.
To actually create and run an instance of our thread class, we must write the following:
MyThread Th=new MyThread();
Th.start();
The first line instantiates a new object of class MyThread.
The second line calls the start() method causing the thread to move into a runnable state.
Example:
// Creating threads using the Thread class
// File Name : ThreadClassDemo.java
import java.io.*;
public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage();
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
Output:
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
12.7 Stopping and Blocking a Thread
Stopping a Thread
The stop() method is used to stop the thread from running further.
Example:
MyThread.stop()
This method causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of its method. The stop() method may be used
when the premature death of the thread is desired.
Blocking a Thread
A thread can be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods:
sleep() // blocked for a specified time
suspend() // blocked until further orders
wait() // blocked until certain condition occurs
These methods cause the thread to go into the blocked (or non-runnable) state. The
thread will return to the runnable state when the specified time is elapsed in the case of
sleep(), the resume() method is invoked in the case of suspend(), and the notify()
method is called in the case of wait().
12.8 Life Cycle of a Thread
A thread moves through several states from its creation to termination. During the
lifetime of a thread, there are many states it can enter. They include:
New
Runnable
Running
Blocked (Waiting)
Dead (Terminated)
A thread is always in one of these five states. It can move from one state to another via a
variety of ways as shown in Figure 12.1.
A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
2) Runnable State
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution. If all threads have equal priority, then they are given time slots for
execution in round robin fashion i.e., first-come, first-serve manner. This process of
assigning time to threads is known as time-slicing.
3) Running State
Running state means that the processor has given its time to the thread for its execution.
A thread can come into running state only from runnable state.
A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleeping,
or waiting in order to satisfy certain requirements.
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
The default priority of the main thread is 5, child thread will take the priority that is
equal to its parent thread priority.
We can change the priority of any thread that it may be the main thread or user-defined
thread.
It is recommended to change the priority by using constants available in the Thread class
like follows:
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
Threads are assigned priorities, based on that the thread scheduler can use to determine
how the thread will be scheduled.
The thread scheduler can use thread priorities to determine which thread gets to run.
setPriority() method
The setPriority() method is used to set the thread’s priority.
The general form is:
ThreadName.setPriority(int newPriority);
Note: The newPriority value range should between 1 to 10 else it leads to exception
java.lang.illegalArgumentException.
Example:
t.setPriority(7); //Valid
t.setPriority(Thread.NORM_PRIORITY+2); //Valid(recommended)
getPriority() method
The getPriority() method is used to obtain the current priority setting.
The general form is:
ThreadName.getPriority();
Example:
// Java program using priority in threads
import java.io.*;
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("Running thread name is:"+Thread.currentThread().getName());
class SyncDemo
{
public static void main(String args[]) throws Exception
{
ThreadX one=new ThreadX();
Thread x= new Thread(one);
Thread y=new Thread(one);
Thread z=new Thread(one);
one.call(x);
one.call(y);
one.call(z);
}
}
Output:
Good Morning
Good Afternoon
Gooed Evening
Good Morning
Good Afternoon
Gooed Evening
Good Morning
Good Afternoon
Gooed Evening
12.11 Interthread Communication
Interthread communication in Java is a technique through which multiple threads
communicate with each other.
It provides an efficient way through which more than one thread communicate with each
other by reducing CPU idle time.
When more than one threads are executing simultaneously, sometimes they need to
communicate with each other by exchanging information with each other. A thread
exchanges information before or after it changes its state.
Interthread communication in Java can be achieved by using three methods provided by
Object class of java.lang package. They are:
1. wait()
2. notify()
3. notifyAll()
These methods can be called only from within a synchronized method or synchronized
block of code otherwise, an exception named IllegalMonitorStateException is thrown.
wait(): This method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).
notify(): This method wakes up the first thread that called wait( ) on the same object.
notifyAll(): This method wakes up all the threads that called wait( ) on the same object
The highest priority thread will run first.
These methods are declared within Object, as shown here:
final void wait() throws InterruptedException
final void notify()
final void notifyAll()
Example:
Output:
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
12.12 Deadlock
Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other.
Deadlock occurs when multiple threads need the same locks but obtain them in different
order.
A Java multithreaded program may suffer from the deadlock condition because the
synchronized keyword causes the executing thread to block while waiting for the lock, or
monitor, associated with the specified object.
Example: