UNIT-IV Multithreading, IO, Applets

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

Multithreading, I/O and Applets

UNIT – IV

MULTI THREADED PROGRAMMING


Introduction
Java provides built-in support for multithreaded programming. A multi-threaded
program contains two or more parts that can run concurrently and each part can
handle a different task at the same time making optimal use of the available resources.
Multi tasking:
Multitasking is a concept of performing multiple tasks (also known as processes)
over a certain period of time by executing them concurrently.

Multi threading:
It is the process of implementing two or more parts of a program to run
concurrently. Each part of such a program is called a thread, and each thread defines a
separate path of execution, thus multithreading is a specialized form of multitasking.

Types of Multi tasking:

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)

Process-based Multitasking
 Each process has its own address in memory i.e. each process allocates separate
memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
 For example, process-based multitasking enables you to run the Java compiler at
the same time that you are using a text editor.

Page 1
Thread-based Multitasking
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
 If you have programmed for operating systems such as Windows, then you are
already familiar with multithreaded programming.
 For instance, a text editor can format text at the same time that it is printing, as
long as these two actions are being performed by two separate threads.

Java Thread Model


Thread:
A thread is defined as a light-weight process that shares the same address space.
Life Cycle of a Thread (Thread States):
A thread can be in one of the five states. The life cycle of the thread in java is controlled
by JVM.
The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
New Thread New Born

stop
start

stop Dea
Active d
Running Runnable Stat
Thread

yield

Suspend
resume
stop
Sleep
Wait notify

Idle Thread
(Not Runnable) Blocked

Fig: 4.2 Life Cycle of a Thread

Following are the stages of the life cycle –

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.
How to create thread

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.

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 the thread.
3. public void sleep(long milliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long milliseconds): waits for a thread to die for the specified
milliseconds.
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.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public void interrupt(): interrupts the thread.
19.public boolean isInterrupted(): tests if the thread has been interrupted.
20.public static boolean interrupted(): tests if the current thread has been
interrupted.

The Main Thread

When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of the program, because it is the one that is executed
when the program begins.
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs
various shutdown actions.
Although the main thread is created automatically when the program is started, it can
be controlled through a Thread object. To do so, we must obtain a reference to it by
calling the method currentThread( ), which is a public static member of Thread.
Its general form is shown here:
static Thread currentThread( )
It returns a reference to the thread in which it is called.
Program: Write a java program to illustrate Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[])
{ Thread t =
Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--)
{ System.out.println(n
);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println("Main thread
interrupted");
}
}
}

Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1

Create a Thread by Extending a Thread Class


To create a new thread, create a new class that extends Thread class using the
following two simple steps.
Step 1
We need to override run( ) method available in Thread class. This method provides an
entry point for the thread and we put the complete business logic inside this method.
Syntax : public void run( )
Step 2
Once Thread object is created, we can start it by calling start() method, which executes
a call to run( ) method.
Syntax: void start( );

Program: Write a java program to create threads by extending Thread class.


// Creating thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new thread by name Demo Thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the thread.
public void run() {
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Child Thread: " +
i); Thread.sleep(500);
}
} catch (InterruptedException e)
{ System.out.println("Child
interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Main Thread: " +
i); Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Create a Thread by implementing Runnable interface.
If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −
Step 1
Implement a run() method provided by a Runnable interface. This method provides an
entry point for the thread and you will put your complete business logic inside this
method.
Following is a simple syntax of the run() method
− public void run( ) { }
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method.
Following is a simple syntax of start() method
− void start();
Program: Write a java program to create threads by implementing Runnable interface.
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e)
{ System.out.println("Child
interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Main Thread: " +
i); Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Creating Multiple Threads


Previously we had been used only two threads: the main thread and one child
thread. However, your program can spawn as many threads as it needs. For example,
the following program creates three child threads:
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--)
{ System.out.println(name + ": " +
i); Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println(name +
"Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e)
{ System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread
should be allowed to run. The higher-priority threads get more CPU time than lower-
priority threads.

A higher-priority thread can also preempt (forceful termination) a lower-priority


one. Threads of equal priority should get equal access to the CPU.

For instance, when a lower-priority thread is running and a higher-priority thread


resumes (from sleeping or waiting on I/O, for example), it will preempt the lower
priority thread.

To set a thread’s priority, use the setPriority( ) method, which is a member of


Thread.

Syntax: final void setPriority(int level)


Here, level specifies the new priority setting for the calling thread. The
value of level must be within the range MIN_PRIORITY and. Currently, the priority
levels are as follows:

public static MIN_PRIORITY 1


public static NORM_PRIORITY 5
public static MAX_PRIORITY 10
These priorities are defined as static final variables within Thread.

Example: t1. setPriority(Thread. MAX_PRIORITY); // t1’s priority is set to 10


t2. setPriority(Thread. NORM_PRIORITY + 2); // t2’s priority is set to 7
Program: Write a java program to illustrate thread priorities.

class TestMultiPriority extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getNam
e());
System.out.println("running thread priority is:"+Thread.currentThread().getPri
ority());
}
public static void main(String args[])
{
TestMultiPriority m1=new TestMultiPriority( );
TestMultiPriority m2=new TestMultiPriority( );
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Using isAlive( ) and join( )
To determine whether a thread has finished, two ways are exist.
First, you can call isAlive( ) on the thread. This method is defined by Thread.
General form: final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still
running. It returns false otherwise.
Second, While isAlive( ) is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join( ).
General form: final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes
from the concept of the calling thread waiting until the specified thread joins it.

Program: Write a java program to illustrate the use of isAlive() and join() methods.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--)
{ System.out.println(name + ": " +
i); Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println(name + "
interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[])
{ NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e)
{ System.out.println("Main thread
Interrupted");
}
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.

Thread Synchronization
When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time. The process
by which this is achieved is called synchronization.
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent inconsistency problem.
Principle: The key principle of synchronization is the concept of the monitor.
Monitor:
A monitor is an object that is used as a mutually exclusive lock, or mutex. Only
one thread can own a monitor at a given time. When a thread acquires a lock, it is said to
have entered the monitor. All other threads attempting to enter the locked monitor will
be suspended until the first thread exits the monitor. These other threads are said to be
waiting for the monitor.
Using Synchronized Methods
To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized method, all other
threads that try to call it (or any other synchronized method) on the same instance have
to wait. To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized method.
Example:
Suppose two different threads are performing two operations writing and
reading a same file at a time. The file should be available to one thread at a time. Hence
the two methods, on which the threads are trying to access a file, must be synchronized.
synchronized public void write(char ch) {
;
}
synchronized public char read( ) {
;
;
}
Interthread Communication
In the above concept, the threads are unconditionally blocked other threads from
asynchronous access to certain methods.
Threads also provide a secondary benefit: they do away with polling. Polling is
usually implemented by a loop that is used to check some condition repeatedly. Once
the condition is true, appropriate action is taken. This wastes CPU time.
To avoid polling, Java includes an elegant inter-thread communication
mechanism via the wait( ), notify( ), and notifyAll( ) methods.
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to enter (or lock) in
the same critical section to be executed. It is implemented by following methods.
These methods are implemented as final methods in Object, so all classes have them.
Note: All three methods can be called only from within a synchronized context.
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.

Method Description
public final void wait() throws
waits until object is notified.
InterruptedException
public final void wait(long timeout) throws waits for the specified amount
InterruptedException 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.
Syntax: public final void notify()
3. notifyAll( ) Method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll( )

Program: Write a java program that correctly implements producer-consumer problem using
the concept of inter thread communication.
Source Code:
class Q
{
boolean valueSet=false;
int n;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception is:"+e);
}
System.out.println("got:"+n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("\n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("\n put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
class ProducerConsumer
{
public static void main(String args[])
{
Q q=new Q();
new
Producer(q);
new Consumer(q);
}
}

Output:
put: 1
got: 1
put: 2
got: 2
put: 3
got: 3
put: 4
got: 4
put: 5
got: 5
Suspending, Resuming, and Stopping Threads

Sometimes, suspending execution of a thread is useful.


For example, a separate thread can be used to display the time of day. If the user doesn’t
want a clock, then its thread can be suspended.
We can use suspend( ) and resume( ), which are methods defined by Thread, to pause
and restart the execution of a thread.
General Form:
final void suspend( );
final void resume( );
Program: Write a java program to illustrate the use suspend, resume methods in
multithreading.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--)
{ System.out.println(name + ": " +
i); Thread.sleep(200);
}
} catch (InterruptedException e)
{ System.out.println(name + "
interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[])
{ NewThread ob1 = new
NewThread("One"); NewThread ob2 = new
NewThread("Two"); try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e)
{ System.out.println("Main thread
Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e)
{ System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
One: 15
New thread: Thread[Two,5,main]
Two: 15
One: 14
Two: 14
One: 13
Two: 13
One: 12
Two: 12
One: 11
Two: 11
Suspending thread One
Two: 10
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
Suspending thread Two
One: 10
One: 9
One: 8
One: 7
One: 6
Resuming thread Two
Waiting for threads to finish.
Two: 5
One: 5
Two: 4
One: 4
Two: 3
One: 3
Two: 2
One: 2
Two: 1
One: 1
Two exiting.
One exiting.
Main thread exiting.
Introduction
I/O Basics
Java I/O (Input and Output) is used to get the input and produce the output. Java
uses the concept of stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.

Stream
A stream is a sequence of data. A stream is an abstraction that either produces or
consumes information. In Java a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
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.

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. 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 System.err.

Byte Streams and Character Streams


Java defines two types of streams:
 ByteStream
 CharacterStream

Byte Streams
 Byte streams provide a convenient means for handling input and output of bytes.
 Byte streams are used, for example, when reading or writing binary data.

Character Streams
 Character streams provide a convenient means for handling input and output of
characters.
 They use Unicode and, therefore, can be internationalized.
The Byte Stream Classes
Byte streams are defined by using two class hierarchies. At the top are two abstract
classes:
 InputStream
 OutputStream.

InputStream Class
InputStream class is an abstract class. It is the super class of all classes
representing an input stream of bytes.
Useful methods of InputStream

Method Description
public abstract int read() throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of file.
returns an estimate of the number of bytes
public int available() throws
that can be read from the current input
IOException
stream.
public void close() throws
is used to close the current input stream.
IOException
InputStream Hierarchy

OutputStream class
OutputStream class is an abstract class. It is the super class of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.
Useful methods of OutputStream

Method Description
public void write(int) throws is used to write a byte to the current
IOException output stream.
public void write(byte[]) throws is used to write an array of byte to the
IOException current output stream.

public void flush() throws IOException flushes the current output stream.

is used to close the current output


public void close() throws IOException
stream.

OutputStream Hierarchy
The Character Stream Classes
Character streams are defined by using two class hierarchies. At the top are two
abstract classes:
 Reader
 Writer
Reader Class
Reader class is an abstract class. It is the super class of all classes representing a
character stream.
Useful methods of Reader class

Method Description

This method closes the stream and releases


abstract void close()
any system resources associated with it.
This method marks the present position in
void mark(int readAheadLimit)
the stream.
This method tells whether this stream
boolean markSupported()
supports the mark() operation.

int read() This method reads a single character.

This method reads characters into an


int read(char[] cbuf)
array.
abstract int read(char[] cbuf, int off, int This method reads characters into a
len) portion of an array.
This method attempts to read characters
int read(CharBuffer target)
into the specified character buffer.
This method tells whether this stream is
boolean ready()
ready to be read.

void reset() This method resets the stream.

long skip(long n) This method skips characters.


Writer Class
Writer class is an abstract class. It is the super class of all classes representing a
character stream.
Useful methods of Writer class

Method Description

This method appends the specified


Writer append(char c)
character to this writer.
This method appends the specified
Writer append(CharSequence csq)
character sequence to this writer.
Writer append(CharSequence csq, int This method appends a subsequence of the
start, int end) specified character sequence to this writer.
This method loses the stream, flushing it
abstract void close()
first.

void write(char[] cbuf) This method writes an array of characters.

abstract void write(char[] cbuf, int off, This method writes a portion of an array of
int len) characters.

void write(int c) This method writes a single character.

void write(String str) This method writes a string.

void write(String str, int off, int len) This method writes a portion of a string.

abstract void flush() This method flushes the stream.


Reader class Hierarchy

Reader

FileReader FilterReader CharArrayReader

BufferedReader PushbackReader InputStreamReader

Writer class Hierarchy

Writer

FileWriter FilterWriter CharArrayWriter

BufferedWriter PrintWriter OutputStreamWriter


Reading Console Input
 The only way to perform console input was to use a byte stream.
 Today, using a byte stream to read console input is still technically possible, but
doing so is not recommended.
 The preferred method of reading console input is to use a character-oriented stream,
which makes a program easier to internationalize and maintain.
 In Java, console input is accomplished by reading from System.in.
 To obtain a character based stream that is attached to the console, wrap System.in
in a BufferedReader object.
 BufferedReader supports a buffered input stream. Its most commonly used
constructoris shown here:
BufferedReader(Reader inputReader);

Here, inputReader is the stream that is linked to the instance of BufferedReader


that is being created.
 One of its concrete subclasses is InputStreamReader, which converts bytes to
characters.
 To obtain an InputStreamReader object that is linked to System.in, use the
following constructor:
InputStreamReader(InputStream inputStream);
System.in refers to an object of type InputStream, it can be used for inputStream.
 Putting it all together, the following line of code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Now, br is a character-based stream that is linked to the console(keyboard)
through System.in.

Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we
will be using is
int read( ) throws IOException

Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of
the BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
Writing Console Output
 Console output is most easily accomplished with print( ) and println( ) methods.
 These methods are defined by the class PrintStream. It is referenced by System.out
which is an object of PrintStream.
 write( ) can be used to write to the console from PrintStream.
void write(int byteval)
This method writes to the stream the byte specified by byteval.

The PrintWriter Class


For real-world programs, the recommended method of writing to the console
when using Java is through a PrintWriter stream.
PrintWriter is one of the character-based classes. Using a character-based class
for console output makes it easier to internationalize a program.
Constructors:
PrintWriter(OutputStream outputStream, boolean flushOnNewline);
Here, outputStream is an object of type OutputStream
flushOnNewline controls whether Java flushes the output stream every time a
println( ) method is called.
Methods:
PrintWriter supports the print( ) and println( ) methods for all types including Object.
To write to the console by using a PrintWriter, specify System.out for the output
stream and flush the stream after each newline.
Ex: PrintWriter pw = new PrintWriter(System.out, true);
Program: Write a program to demonstrate PrintWriter.
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Output:
This is a string
-7
4.5E-7

Reading and Writing Files

 Java provides a number of classes and methods that allow you to read and write
files.
 In Java, all files are byte-oriented, and provides methods to read and write bytes
from and to a file.
 Two of the most often-used stream classes are FileInputStream and
FileOutputStream, which create byte streams linked to files.
 To open a file, you simply create an object of one of these classes, specifying the
name of the file as an argument to the constructor.
Ex: FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
Note: When an output file is opened, any preexisting file by the same name is
destroyed.
 When we are done with a file, we should close it by calling close( ) as follows:
void close( ) throws IOException
Reading a File
To read from a file, we use a version of read( ) that is defined within
FileInputStream.
int read( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte
as an integer value.
read( ) returns –1 when the end of the file is encountered.
Program: Write a java program to read the content of a file, the name of the file is
passed as command line argument.
import java.io.*;
class ShowFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e)
{ System.out.println("File Not
Found"); return;
} catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Usage: ShowFile
Filename"); return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}

Output:
/*
Display a text file you want, pass it’s file name as command-line argument.
Ex: java ShowFile test.txt
*/
Writing a File
To write to a file, we can use the write( ) method defined by FileOutputStream as
follows:
void write(int byteval) throws IOException
This method writes the byte specified by byteval to the file. Although byteval is declared
as an integer, only the low-order eight bits are written to the file. If an error occurs
during writing, an IOException is thrown.
Program: Write a java program to write the content of one file to another file, the name
of the files are passed as command line arguments.
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e)
{ System.out.println("Input File Not
Found"); return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e)
{ System.out.println("Error Opening Output
File"); return;
}
} catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Usage: CopyFile From
To");
return;
}
// Copy File
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e)
{ System.out.println("File
Error");
}
fin.close();
fout.close();
}
}

Output:
/*
For copying, pass source file name and destination file name as command-line
arguments.
Ex: java CopyFile source.txt dest.txt
*/
APPLETS
Introduction:
Applet – Definition:
Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a web document.
An applet is a Java program that runs in a Web browser.
Applets are designed to be embedded within an HTML page to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.
Differences between Applets and Applications

FEATURE APPLICATION APPLET

main()
Present Not present
method

Requires a java enables web


browser like Chrome, Netscape
Execution Requires JRE
Navigator, Opera, HotJava and so
on.

Called as stand-alone application


Requires some third party tool
Nature as application can be executed
help like a browser to execute
from command prompt.

Can access any data or software cannot access anything on the


Restrictions
available on the system system except browser’s services.

GUI GUI is incorporated explicitly GUI is readily available.

HTML No HTML file is required HTML file is required

Requires highest security for the


Security Does not require any security
system as they are untrusted
Applet Lifecycle or Applet Skeleton
Every applet is in one of the following states during it’s lifetime.
1. Born State.
2. Running State
3. Idle State
4. Dead State
The following figure shows the lifecycle of an applet.

Four methods in the Applet class of java.applet package gives us the framework to build
an applet.
1. init( )
2. start( )
3. stop( )
4. destroy( )
1. New Born State: (Initialization State)
 Applet enters to this state when it is first loaded by calling init() method.
 In this stage, we will do the following:
1. Create objects needed by applet
2. Setup initial values
3. Load images and fonts
4. Setup colors.
 We should override init( ) method as follows:
 publi void init( ) {...................}
 This method is called only once during the lifetime of the applet.
2. Runnning State
 Applet enters this state when the system calls start( ) method.
 It calls automatically, once the applet is initialized.
 It also moves an idle applet to running state.
 If required, this method can be overrided as
follows: public void start( )
{
----------// @override@ ------------
}
3. Idle or Stopped State
 An applet becomes idle when it is stopped from running.
 Stopping occurs automatically when we leave the page containing the
currently running applet then stop( ) method is invoked.
 If required, this method can be overrided as
follows: public void stop( )
{
----------// @override@ ------------
}
4. Dead State
 An applet is said to be dead, when it is removed from memory.
 It occurs automatically by invoking the destroy( ) method when we quit
the browser.
 If required, this method can be overrided as
follows: public void destroy( )
{
----------// @override@ ------------
}
5. Display State
 Applet moves to this state whenever it has to perform some output operations
on the screen.
 The paint( ) is called to display.
 It is called after the applet enter into the running state.
 Every applet will have a paint( ) method and it must be overrided as
follows: public void paint(Graphics g)
{
----------// @override@ ------------
}
 The paint( ) method takes one parameter of type Graphics and it
contains graphics context.
Applet Class
 Every applet is a sub class of Applet class of java. applet package, hence to design
an applet, Applet class must be extended.
 Following figure shows the chain of classes inherited by Applet class.

Building an Applet Code


Applet code uses the services of two classes: Applet and Graphics class of java.applet
and java.awt package respectively. Hence they must be imported.
General Format:
import java.applet.Applet;
import java.awt.Graphics;
public class ClassNameApplet extends Applet {
public void paint(Graphics g)
{
----------------------------------------
----------------------------------------

}
}
Executing an Applet
Two ways: 1. Using Web Browser
2. Using appletviewer command
1. Using Web Browser
-- Build applet code (.java file)
-- Compile applet code (.class file)
-- create HTML file (.html file)

<HTML>

<applet code = ".class file" height = 100 width = 150>

</applet>

</HTML>

2. Using appletviewer command


 To view and test an applet more conveniently during development stage, we can
use appletviewer command at command prompt.
 Simply include a comment at the head of the java sourcefile that contains the
<APPLET> tag.
/* <HTML>
<applet code=".class file" height=100 width=150>
</applet>
</HTML> */
Program: Develop an applet that displays a simple message.
Source Code:

import java.applet.Applet;
import java.awt.Graphics;
/* <HTML>
<Applet code="Message.class" height=100 width=150>
</Applet>
</HTML> */

public class Message extends Applet {


public void paint(Graphics g)
{
g.drawString("welcome to applets",10,100);
}
}
Output:
At command prompt
E:\sudheer> javac Message.java
E:\sudheer> appletviewer Message.java

Simple Applet Display Methods


 Applets are displayed in a window, and AWT-based applets use the AWT to
perform input and output.
To output a string to an applet, use drawString( ), which is a member of the Graphics
class.
Syntax: void drawString(String message, int x, int y);
message: Text to be displayed on the applet.
x, y: Coordinates where the message to be displayed.
It is called from within either update( ) or paint( ).
Note: In a Java window, the top-left corner is location (0,0).

To set background and foreground color of an applet, use setBackground( ) and


setForeground( ) respectively, which is a member of the Component class.

Syntax: void setBackground(Color newColor);


void setForeground(Color newColor);
Here, newColor specifies the new color.
The class Color defines the constants shown in the next slide that can be used to specify
colors:

Color. black Color. magenta Color. blue


Color. orange Color. cyan Color. pink
Color. darkGray Color. red Color. gray
Color. white Color. green Color. yellow
Color. lightGray

Note: A good place to set the foreground and background colors is in init( ) method.

Program: Design a simple applet that sets the foreground and background colors and
outputs a string.

import java.awt.*;
import java.applet.*;

/* <applet code="Sample" width=300 height=50> </applet> */

public class Sample extends Applet


{ String msg;
// set the foreground and background colors.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start() {
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
Output:
At command prompt
E:\sudheer> javac Sample.java
E:\sudheer> appletviewer Sample.java

Requesting Repainting

An applet writes to its window only when its update( ) or paint( ) method is called by
the AWT.
How can the applet itself cause its window to be updated when its information changes?
The paint() method is called by the JVM implicitly in two circumstances.
 When the first time frame is created and displayed.
 When the frame is resized (by dragging the frame border with mouse) by the
user.
If the programmer would like to call the paint( ) method in the middle of the coding, it is
permitted to call repaint() method and not permitted to call paint( ) method directly.
What is the designing secret in not allowing paint() to call directly?
Calling paint( ) method raises compilation error. Before the window is to be
drawn with new data, the old data must be erased, else, both overwrite the other and
finally the data is not readable. This automatic erasing is done by the repaint() method.
repaint(): The repaint() method calls automatically update() method and in turn the
update() method calls paint() method.
The repaint( ) method is defined by the AWT. Thus, to update an applet, simply store
the output and then call repaint( ).
The repaint( ) method has four forms.
 void repaint( ); causes the entire window to be repainted.
 void repaint(int left, int top, int width, int height); causes the specified region
will be repainted.
Here, left and top- the coordinates of the upper-left corner of the region
width and height of the region are passed in width and height.
 void repaint(long maxDelay);
 void repaint(long maxDelay, int x, int y, int width, int height);
Here, maxDelay specifies the maximum number of milliseconds that can elapse
before update( ) is called.
Program: Write a java program to design a simple moving banner applet.
/* A simple banner applet. This applet creates a thread that scrolls the message
contained in msg right to left across the applet's window. */
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
public class SimpleBanner extends Applet implements Runnable {
String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
// Set colors and initialize thread.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner.
public void run() {
char ch;
// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}
}
// Pause the banner.
public void stop() {
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}
}

Output:
At command prompt
E:\sudheer> javac SimpleBanner.java
E:\sudheer> appletviewer SimpleBanner.java
Using the Status Window
An applet can also output a message to the status window of the browser or
applet viewer on which it is running.
It is required to call showStatus( ) with the string that you want displayed in a status
window.
The status window is a good place to
 Give the user feedback about what is occurring in the applet
 Suggest options
 Possibly report some types of errors
Program: Write a java program to demonstrate the status window of an applet.
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet{
public void init() {
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

Output:
At command prompt
E:\sudheer> javac StatusWindow.java
E:\sudheer> appletviewer StatusWindow.java

You might also like