Java & DS UNIT 3 Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

SE23A| JAVA AND DATA STRUCTURES

UNIT - III Packages - Access Protection - Importing Packages - Interfaces - Exception


Handling - Throw and Throws-The Java Thread Model- Creating a Thread and Multiple
Threads - Thread Priorities Synchronization-Inter thread Communication - Deadlock -
Suspending, Resuming and stopping threads – Multithreading-I/O Streams - File Streams -
Applets .

3.1 PACKAGE IN JAVA


Package in java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
Preventing naming conflicts.
For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
■ Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
■ Providing controlled access: protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses.
A default member (without any access specifier) is accessible by classes in the same
package only.
■ Packages can be considered as data encapsulation (or data-hiding).

3.1.1 Types
In java, the packages have divided into two types.
■ Built-in Packages
■ User-defined Packages
3.1.1.1 Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-
defined classes, interfaces, and sub-packages. The built-in packages were included in the
JDK.There are many built-in packages in java, few of them are as java, lang, io, util, awt,
javax, swing, net, sql, etc.
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button

1
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

, ;menus etc).
6) java.net: Contain classes for supporting networking operation.

3.1.1.2 User-defined Packages

■ The user-defined packages are the packages created by the user. User is free to create
their own packages.
3.1.1.3 Naming Convention
While choosing a package name you need to keep the following points in mind.
■ The name of the package should be in small letters.
■ It is suggested to start the name of the package with the top level domain level followed
by sub domains, ex: com.example.tutorialspoint
3.1.2 Defining and Creating a Package in java
step1: simply include a package command has the first statement in java source file.
Any class you declare with in that file will belong to the specified package.
syntax: package packagename;
Eg: package mypack;
step 2: next define the class that is to be put in the package and declare it as public
step 3: now store the classname.java file in the directory having name same as package name.
step 4: file is to be compiled, which creates .class file in the directory
java also supports the package hierarchy , which allows to group related classes
into a package and then group related packages into a larger package.
We can achieve this by specifying multiple names in a package statement,
separated by dot . i.e., package firstpackage.secondpackage;

2
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

3.1.3 Accessing package

A java system package can be accessed either using a fully qualified classname or
using import statement.
We generally use import statement.
syntax:
import pack1[.pack2][.pack3].classname;

or

import pack1. [.pack2][.pack3].*;

3.1.4 Adding a class to a Package


Add more classes to a created package by using package name at the top of the
program and saving it in the package directory.
We need a new java file to define a public class, otherwise we can add the new
class to an existing .java file and recompile it.
3.1.4.1 Subpackages
Packages that are inside another package are the subpackages. These are not imported
by default, they have to imported explicitly. Also, members of a subpackage have no access
privileges, i.e., they are considered as different package for protected and default access
specifiers.
3.1.4.2 Understanding CLASSPATH
The package hierarchy is controlled by CLASSPATH. Until now we have been
storing all of our classes in the same unnamed default package.
This works because the default current working directory(.) is usually in the
class path environmental variable defined for the java runtime system by
default.
3.1.5 Importing Packages in java
■ In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.
■ The import statement must be after the package statement, and before any other statement.
3.1.5.1 Importing specific class
■ Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.
Syntax: import packageName.ClassName;
3
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

3.1.5.2 Importing all the classes


■ Using an importing statement, we can import all the classes of a package. To import
all the classes of the package, we use * symbol. The following syntax is employed
to import all the classes of a package.
Syntax: import packageName.*;
Example:

package myPackage;
import java.util.Scanner ;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
}
}

3.1.6 Hiding Classes


When we import a package using astric(*),all public classes are imported.however ,we may
preffer to “not import”certain classes.i.e,we may like to hide these classes from accessing from
outside of the package.such classes should be declared”not public”.
Example:
package p1;
public class X
{
Body of X
}
class Y
{
Body of Y
}
3.1.7 Example Program for Package
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}

4
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

3.2 INTERFACE
An interface is a special case of abstract class, which contains all the abstract methods (methods
without their implementation).
• An interface specifies what a class must do, but not how to do.
• Using the keyword interface, we can fully abstract a class interface from its implementation.
• Interfaces are syntactically similar to classes, but they lack instance variable, and their
methods are declared without anybody.
• Once it is defined, any number of classes can implement an interface. Also, once
class can implement any number of interfaces.
3.2.1 Initializing interface
• An interface is defined much like a class.
• This is the general form of an interface:
access interface interface_name
{
type final_varname1=value;
type final_varname2=value;
. . . .
returntype method-name1(parameter_list);
returntype method-name2(parameter_list);
. . . .
5
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

Eg:
Interface
{
int pcode=999; // final variable
String pname=”HardDisk”; // final variable
void show(); // abstract method
}

3.2.2 Extending Interface


Like classes, interfaces can also be extended. That is an interface can be subinterfaced from other
interfaces.
• The new subinterface will inherit all the members of the superinterface in the manner similar to
subclasses.
• This is achieved using the keyword extends as shown below
Syntax:
interface name2 extends name
{
body of name2;
}

Example:
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{

void display();
}
class display implements Item
{
public void display()
{
System.out.println(code+”:”+name);
}
}

3.2.3 Implementing interfaces


• Once an interface has been defined, one or more lases 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:

6
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

Syntax:
access class classname [extends superclass][implements interface
[,interface…]]
{
class body
}
Example:
interface product
{
int pcode=999;
String pname=”HardDisk”;
abstract void showProduct();
}
class ProductDesc implements Product
{
public void showProduct()
{
System.out.println(“Pcode=”+pcode);
System.out.println(“PName=”+pname);
}
}
class DemoInterface
{
public static void main(String ar[])
{
ProductDesc ob=new
ProductDesc();
ob.showProduct();
}
}
Variables in interface:
• Interfaces can also be used to declare a set of constants that can be used in different classes.
• The constant values will be available to any class that implements the interface.
• The values can be used in any method, as part of any variable declaration, or anywhere
where we can use a final value.
Example:
interface A
{
int m=10, n=50;
}
class B implements A
{
void display()
{
System.out.println(“m=”+m+” , n=”+n);
}
}

7
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

3.3 EXCEPTION HANDLING

The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

3.3.1 What is exception


In java, exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.

3.3.2 Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling.

3.3.3 Types of Exception

There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says there are
three types of exceptions:
1. CheckedException
2. UncheckedException
3. Error

Difference between checked and unchecked exceptions


 Checked Exception: The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.

 Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
 Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionErroretc.
3.3.4 Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

Java try block must be followed by either catch or finally block.

8
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

Syntax of java try-catch

try
{
//code that may throw exception
}
catch(Exception_class_Name ref){ }
Syntax of try- finallyblock
try{
//code that may throwexception
}
finally{}
3.3.4.1 Java catch block

Java catch block is used to handle the Exception. It must be used after
the try block only. You can use multiple catch block with a single try.
Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1


{
public static void main(String args[])
{
int data=50/0; //may throw exception
System.out.println("rest of thecode...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ byzero
3.3.5 Solution by exception handling

Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{


public static void main(String args[])
{ try{
9
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

int data=50/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
System.out.println("rest of the code...");
} }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

3.3.6 Java Multi catch block

If you have to perform different tasks at the occurrence of different


Exceptions, use java multi catch block.

Let's see a simple example of java multi-catch block.

public class
TestMultipleCatchBlock{ pu
blic static void
main(Stringargs[]){ try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{ System.out.println("task1 iscompleted"); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("task 2 completed"); }
catch(Exception e)
{ System.out.println("common taskcompleted") ;
}
System.out.println("rest of the code...");
}}

3.3.7 Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[])
{
try{
10
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

try{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
try{
t a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e);}
System.out.println("other statement);
}
catch(Exception e)
{ System.out.println("handeled"); }
System.out.println("normal flow..");
}
3.3.8 Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or unchecked exception in java by throw


keyword. The throw keyword is mainly used to throw custom exception. We will
see custom exceptions later.

The syntax of java throw keyword is given below.


throw exception;
3.3.8.1 Java throw keyword example
In this example, we have created the validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the ArithmeticException.
otherwise print a message welcome to vote.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
11
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

{
validate(13);
System.out.println("rest of the code...");
} }

Output:
Exception in thread main java.lang.ArithmeticException:notvalid
3.3.9 Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information


to the programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there


occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.

Syntax of java throws


return_type method_name() throwsexception_class_name
{}

3.3.9.1 Java throws example


Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{ m(); }
void p()
{
try{ n(); }
catch(Exception e)
{ System.out.println("exception handled");}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
} }
12
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

3.4 JAVA THREAD MODEL


The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time. This type of program is known as a
multithreading program. Each part of this program is called a thread. Every thread defines a
separate path of execution in java. A thread is explained in different ways, and a few of them are
as specified below.
A thread is a light weight process
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.

3.4.1 Life Cycle of a Thread


In java, a thread goes through different states throughout its execution. These stages are
called thread life cycle states or phases. A thread may in any of the states like new, ready or
runnable, running, blocked or wait, and dead or terminated state.
The life cycle of a thread in java is shown in the following figure.

New
When a thread object is created using new, then the thread is said to be in the New state.
This state is also known as Born state.
Example

Thread t1 = new Thread();

Runnable / Ready
13
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state.
Example

t1.start( );

Running
When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.

Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume(
) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspend();
notify();
notifyAll();
resume();

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.
3.4.2 Creating a Thread
In java, a thread is a lightweight process. Every java program executes by a thread called
the main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Using Runnable interface (by implementing Runnable interface)

Let's see how to create threads using each of the above.

14
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

3.4.2.1 Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class contains
all the methods that are related to threads.
To create a thread using Thread class, follow the step given below.

 Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Call the start( ) method on the object created in the above step.

Example
class SampleThread extends Thread{
public void run() {
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class My_Thread_Test {
public static void main(String[] args)
{ SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}}
3.4.2.2 Runnable Interface:
The java contains a built-in interface Runnable inside the java.lang package. The
Runnable interface implemented by the Thread class that contains all the methods that are related
to the threads.
To create a thread using Runnable interface, follow the step given below.

 Step-1: Create a class that implements Runnable interface.


 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter to
the Thread class constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.

15
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

class SampleThread implements Runnable


{ public void run() {
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}}}
public class My_Thread_Test {
public static void main(String[] args) {
SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
} }
Commonly used Constructors of Thread class:

Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on
thethread.
3. public void sleep(long miliseconds): Causes the currently executing thread
to sleep(temporarily cease execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread todie.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).

16
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

16. public void resume(): is used to resume the suspended thread(depricated).


17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

3.4.3 Thread Priority


In a java programming language, every thread has a property called priority. Most of
the scheduling algorithms use the thread priority to schedule the execution sequence. In java,
the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority
10 is considered as the highest priority. The thread with more priority allocates the processor
first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and they are
listed below.

 MAX_PRIORITY - It has the value 10 and indicates highest priority.


 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority.

3.4.3.1 setPriority( ) method


The setPriority( ) method of Thread class used to set the priority of a thread. It takes an
integer range from 1 to 10 as an argument and returns nothing (void).
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);

3.4.3.2 getPriority( ) method


The getPriority( ) method of Thread class used to access the priority of a thread. It does
not takes anyargument and returns name of the thread as String.
String threadName = threadObject.getPriority();
Example
class SampleThread extends Thread
{ public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
17
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

Thread.currentThread().getName());
}}
public class My_Thread_Test {
public static void main(String[] args) {
SampleThread threadObject1 = new SampleThread(); SampleThread
threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second"); threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}}
3.4.3.3 Java Thread Synchronization
The java programming language supports multithreading. The problem of shared
resources occurs when two or more threads get execute at the same time. In such a situation, we
need some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.
In java, the synchronization is achieved using the following concepts.

 Mutual Exclusion
 Inter thread communication

In this tutorial, we discuss mutual exclusion only, and the inter thread communication will be
discussed in the next tutorial.

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.

 Synchronized method
 Synchronized block

Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at a
time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.
In the below image, initially the thread-1 is accessing the synchronized method and other
18
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.

EXAMPLE:

class Table{
synchronized void printTable(int n)
{
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
class MyThread_1 extends Thread
{
Table table = new Table();
int number;
MyThread_1(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
class MyThread_2 extends Thread{ Table table = new Table();
int number;
MyThread_2(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
19
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

}
}
public class ThreadSynchronizationExample
{
public static void main(String[] args)
{
Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}
3.4.4 Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
3.4.5 Java Inter Thread Communication
Inter thread communication is the concept where two or more threads communicate to
solve the problem of polling. In java, polling is the situation to check some condition repeatedly,
to take appropriate action, once the condition is true. That means, in inter-thread communication,
a thread waits until a condition becomes true such that other threads can execute its task. The
inter-thread communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.

 wait( )
 notify( )
 notifyAll( )

The following table gives detailed description about the above methods.

Method Description

It makes the current thread to pause its execution until other thread in
void wait( ) the same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

Example:
20
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}
catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{c.withdraw(15000);}
}.start();
new Thread()
{
public void run()
{c.deposit(10000);}
}.start();
}
}
3.5 DEADLOCK IN JAVA

Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a


thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each
21
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

other to release the lock, the condition is called deadlock.

Example:
Program with DEAD LOCK:
package thread;
public class ResolveDeadLockTest { public static void main(String[]
args) {
ResolveDeadLockTest test = new ResolveDeadLockTest();

final A a = test.new A(); final B b = test.new B();

// Thread-1
Runnable block1 = new Runnable() { public void run() {
synchronized (a) { try {
// Adding delay so that both threads can start trying to
// lock resources Thread.sleep(100);
} catch (InterruptedException e) { e.printStackTrace();
}
// Thread-1 have A but need B also synchronized (b) {
System.out.println("In block 1");
}
}
}
};
// Thread-2
Runnable block2 = new Runnable() { public void run() {
synchronized (b) {

22
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

// Thread-2 have B but need A also synchronized (a) {


System.out.println("In block 2");
}
}
}
};

new Thread(block1).start();
new Thread(block2).start();
}

// Resource A private class A {


private int i = 10;

public int getI() { return i;


}

public void setI(int i) { this.i = i;


}

// Resource B
private class B {
private int i = 20;

public int getI() { return i;


}

public void setI(int i) { this.i = i;


}
}
}

AVOIDING THREAD

Runnable block1 = new Runnable()


{ public void run() {
synchronized (b)
{ try {
// Adding delay so that both threads can start trying to
// lock resources
Thread.sleep(100);
}
catch (InterruptedException e)
{ e.printStackTrace();
}
23
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

// Thread-1 have A but need B also synchronized (a) {


System.out.println("In block 1");
}
}
}
};
// Thread-2
Runnable block2 = new Runnable()
{ public void run() {
synchronized (b) {
// Thread-2 have B but need A also synchronized (a) {
System.out.println("In block 2");
}
}
}
};

How to Avoid Deadlock in Java


Deadlocks cannot be completely resolved. But we can avoid them by following basic
rules mentioned below:
Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main
reason for a deadlock condition. It normally happens when you give locks to multiple threads.

Avoid Unnecessary Locks: The locks should be given to the important threads.
Giving locks to the unnecessary threads that cause the deadlock condition.

Using Thread Join: A deadlock usually happens when one thread is waiting for the other
to finish. In this case, we can use join with a maximum time that a thread will take.

SUSPENDING,RESUMING AND STOPING A THREAD:


Java Thread suspend() method

The suspend() method of thread class puts the thread from running to waiting state. This method
is used if you want to stop the thread execution and start it again when a certain event occurs.
This method allows a thread to temporarily cease execution. The suspended thread can be
resumed using the resume() method.Syntax
public final void suspend()

Java Thread resume() method

The resume() method of thread class is only used with suspend() method. This method is used to
resume a thread which was suspended using suspend() method. This method allows the
suspended thread to start again.

Syntax

24
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

public final void resume()

Java Thread stop() method

The stop() method of thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by start() method.Syntax

public final void stop()

public final void stop(Throwable obj)

Parameter

obj : The Throwable object to be thrown.


3.6 Java - Files and I/O

The java.io package contains nearly every class you might ever need to perform input
and output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
3.6.1 Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file −
Example
25
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

import java.io.*; public


class CopyFile
{
public static void main(String args[]) throws IOException
{ FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c =
in.read()) != -1)
{ out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null)
{ out.close();
}
}
}
}
Now let's have a file input.txt with the following content − This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following –
$javac CopyFile.java
$java CopyFile

3.6.2 Character Streams


Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there are
many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
26
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

public class CopyFile


{

public static void main(String args[]) throws IOException


{ FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c =
in.read()) != -1)
{ out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content − This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile

3.6.3 Standard Streams


All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are aware
of C or C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard streams −
 Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented as System.in.
 Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
 Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as

27
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "q" −
Example
import java.io.*;
public class ReadConsole
{
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown
in the following program. This program continues to read and output the same character until
we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

3.6.4 Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is
used to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

28
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

The two important streams are FileInputStream and FileOutputStream,.


FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new
FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
Sr.No. Method &
Description

1
public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
file output stream is called when there are no more references to this stream. Throws
an IOException.

3
public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.

4
public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.

5
29
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.
 ByteArrayInputStream
 DataInputStrea
m FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a
file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file − OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

Sr.No. Method &


Description
public void close() throws IOException{}
1
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
public void write(int w)throws IOException{}
3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4
Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following
links −
 ByteArrayOutputStream

30
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

 DataOutputStream
Following is the example to demonstrate InputStream and OutputStream −
import java.io.*;
public class fileStreamTest {
public static void main(String args[])
{ try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++)
{
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i = 0; i < size; i++)
{ System.out.print((char)is.read() + " ");
}
is.close();
}
catch (IOException e)
{ System.out.print("Exception");
}
}

3.7 JAVA APPLET


An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.

31
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
3.7.1 Life Cycle of an Applet
Four methods in the Applet class gives you the framework on which you build any serious applet.
 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
 stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
A "Hello, World" Applet
Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class −

 java.applet.Applet
 java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
3.7.2 The Applet Class
Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and services from
the browser context.
These include methods that do the following −
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
32
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

 Print a status message in the browser


 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may −
 Request information about the author, version, and copyright of the applet
 Request a description of the parameters the applet recognizes
 Initialize the applet
 Destroy the applet
 Start the applet's execution
 Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.
How to run an Applet?
There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
33
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java c:\>appletviewer First.java
3.7.3 Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
34
PERI COLLEGE OF ARTS AND SCIENCE
SE23A| JAVA AND DATA STRUCTURES

10. public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

3.7.4 Painting in Applet

We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener

Example of Painting in Applet:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>

35
PERI COLLEGE OF ARTS AND SCIENCE

You might also like