0% found this document useful (0 votes)
2 views28 pages

Java Unit III

The document provides an overview of Java exceptions, categorizing them into checked exceptions, unchecked exceptions, and errors, along with their handling mechanisms. It explains the use of try, catch, throw, throws, and finally keywords for exception handling, and illustrates how to create user-defined exceptions. Additionally, it covers Java's file I/O operations, detailing byte and character streams, and standard input/output streams.

Uploaded by

Jwala Jose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Java Unit III

The document provides an overview of Java exceptions, categorizing them into checked exceptions, unchecked exceptions, and errors, along with their handling mechanisms. It explains the use of try, catch, throw, throws, and finally keywords for exception handling, and illustrates how to create user-defined exceptions. Additionally, it covers Java's file I/O operations, detailing byte and character streams, and standard input/output streams.

Uploaded by

Jwala Jose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

BCA - JAVA

YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH


PRORAMMING

JAVA – EXCEPTIONS
An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.

 A user has entered an invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications or the JVM has run out
of memory

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner

Based on these, we have three categories of Exceptions.

 Checked exceptions − A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.

 Unchecked exceptions − An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

 Errors − These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
1
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

EXCEPTION HANDLING
 Default Exception Handling : Whenever inside a method, if an exception has occurred, the
method creates an Object known as Exception Object and hands it off to the run-time
system(JVM). The exception object contains name and description of the exception, and
current state of the program where exception has occurred. Creating the Exception Object and
handling it to the run-time system is called throwing an Exception.There might be the list of
the methods that had been called to get to the method where exception was occurred. This
ordered list of the methods is called Call Stack.Now the following procedure will happen.
 The run-time system searches the call stack to find the method that contains block of
code that can handle the occurred exception. The block of the code is called Exception
handler.
 The run-time system starts searching from the method in which exception occurred,
proceeds through call stack in the reverse order in which methods were called.
 If it finds appropriate handler then it passes the occurred exception to it. Appropriate
handler means the type of the exception object thrown matches the type of the
exception object it can handle.
2
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 If run-time system searches all the methods on call stack and couldn’t have found the
appropriate handler then run-time system handover the Exception Object to default
exception handler , which is part of run-time system. This handler prints the exception
information in the following format and terminates program abnormally.

 Customized Exception Handling: Java exception handling is managed via five


keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program
statements that you think can raise exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown. Your code can catch this exception (using catch block)
and handle it in some rational manner. System-generated exceptions are automatically thrown
by the Java run-time system. To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by a throws clause. Any
code that absolutely must be executed after a try block completes is put in a finally block.

CATCHING EXCEPTIONS

A method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred
to as protected code, and the syntax for using try/catch looks like the following −

Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of
exception that occurred is listed in a catch block, the exception is passed to the catch block much as
an argument is passed into a method parameter.

Example
public class MyClass {
3

public static void main(String[ ] args) {


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:

Something went wrong.

MULTIPLE CATCH BLOCKS

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like
the following −

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

THE THROWS/THROW KEYWORDS

If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by
4

using the throw keyword.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Try to understand the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.

The following method declares that it throws a RemoteException −

Example
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException −

Example
import java.io.*;
public class className {

public void withdraw(double amount) throws RemoteException, InsufficientFundsException


{
// Method implementation
}
// Remainder of class definition
}

THE FINALLY BLOCK

The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no
5

matter what happens in the protected code.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

A finally block appears at the end of the catch blocks and has the following syntax −

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
6
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Note the following −

 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses whenever a try/catch block is present.

 The try block cannot be present without either catch clause or finally clause.

 Any code cannot be present in between the try, catch, finally blocks.

USER-DEFINED CUSTOM EXCEPTION IN JAVA

User Defined Exception or custom exception is creating your own exception class and throws that
exception using ‘throw’ keyword. This can be done by extending the class Exception. There is no
need to override any of the above methods available in the Exception class, in your derived class. But
practically, you will require some amount of customizing as per your programming needs.

Example:

class MyException extends Exception {


String s1;
MyException(String s2) {
s1 = s2;
}
public String toString() {
return ("Output String = "+s1);
}
}
public class NewClass {
public static void main(String args[]) {
try {
throw new MyException("Custom message");
} catch(MyException exp) {
System.out.println(exp);
}
}
}
Result
The above code sample will produce the following result.

Output String = Custom message


7
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

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.
8
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

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) {
9
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

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.*;
public class CopyFile {

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


10

FileReader in = null;
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

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
11
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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 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();
}
}
}
12

}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

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.

The two important streams are FileInputStream and FileOutputStream, which would be discussed
in this tutorial.
13
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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
public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.
14
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

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 void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.

4
public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.

Example

Following is the example to demonstrate InputStream and OutputStream −


15

import java.io.*;
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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");
}
}
}

The above code would create file test.txt and would write given numbers in binary format. Same
would be the output on the stdout screen.

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.

The important points about BufferedInputStream are:


16
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

o When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration

Let's see the declaration for Java.io.BufferedInputStream class:

public class BufferedInputStream extends FilterInputStream

Java BufferedInputStream class constructors

Constructor Description

BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it


argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified


int size) buffer size and saves it argument, the input stream IS,
for later use.

Java BufferedInputStream class methods

Method Description

int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input
stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified
off, int ln) byte array, starting with the given offset.
17

void close() It closes the input stream and releases any of the system resources
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

associated with the stream.

void reset() It repositions the stream at a position the mark method was last called
on this input stream.

void mark(int It sees the general contract of the mark method for the input stream.
readlimit)

long skip(long x) It skips over and discards x bytes of data from the input stream.

boolean It tests for the input stream to support the mark and reset methods.
markSupported()

Example of Java BufferedInputStream

Let's see the simple example to read data of file using BufferedInputStream:

package com.javatpoint;

import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
18
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Java BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to
store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax
for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testo


ut.txt"));

Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream

Java BufferedOutputStream class constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which


is used for writing the data to the specified
output stream.

BufferedOutputStream(OutputStream os, It creates the new buffered output stream which


int size) is used for writing the data to the specified
output stream with a specified buffer size.

Java BufferedOutputStream class methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.
19
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

void write(byte[] b, int It write the bytes from the specified byte-input stream into a specified
off, int len) byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object which is
connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into
another. It is required if you have connected the one stream with another.

package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
} }

Output:

Success

READING DATA FROM KEYBOARD

There are many ways to read data from the keyboard. For example:

 InputStreamReader
20

 Console
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 Scanner
 DataInputStream etc.

InputStreamReader class

InputStreamReader class can be used to read data from keyboard.It performs two tasks:

 connects to input stream of keyboard


 converts the byte-oriented stream into character-oriented stream

BufferedReader class

BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and BufferdReader class

In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for
reading the line by line data from the keyboard.

import java.io.*;
class G5{
public static void main(String args[])throws Exception{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Amit
Welcome Amit
21
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

JAVA - MULTITHREADING

Java is a multi-threaded programming language which means we can develop multi-threaded


program using Java. 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 specially when your computer has multiple CPUs.By definition, multitasking is when
multiple processes share common processing resources such as a CPU. Multi-threading extends the
idea of multitasking into applications where you can subdivide specific operations within a single
application into individual threads. Each of the threads can run in parallel. The OS divides processing
time not only among different applications, but also among each thread within an application.

Multi-threading enables you to write in a way where multiple activities can proceed concurrently in
the same program.

LIFE CYCLE OF A THREAD / THREAD STATES

A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle Example
of a thread.

Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

 Runnable − After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
22
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.

 Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.

 Terminated (Dead) − A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

Create a Thread by Implementing a 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

As a first step, you need to 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();

THREAD METHODS

Following is the list of important methods available in the Thread class.


23
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Sr.No. Method & Description

1
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this
Thread object.

2
public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is
invoked on that Runnable object.

3
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the
name.

4
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.

5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.

6
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to
block until the second thread terminates or the specified number of milliseconds passes.

7
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but
before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the currently
running thread.
Sr.No. Method & Description

1
public static void yield()
24
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Causes the currently running thread to yield to any other threads of the same priority that
are waiting to be scheduled.

2
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of
milliseconds.

3
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.

4
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this
method.

5
public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.

How to Create a Java Thread


Java lets you create a thread one of two ways:
 By implementing the Runnableinterface.
 By extending the Thread.
Let's look at how both ways help in implementing the Java thread.
Runnable Interface
The easiest way to create a thread is to create a class that implements the Runnable interface. To
implement Runnable interface, a class need only implement a single method called run( ), which is
declared like this:
public void run( )

Inside run( ), we will define the code that constitutes the new thread. Example:
public class MyClass implements Runnable
{
public void run()
{
25

System.out.println("MyClass running");
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

}
}
To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor
(A constructor in Java is a block of code similar to a method that's called when an instance of an object
is created).
Here is how that is done:
Thread t1 = new Thread(new MyClass ());
t1.start();

When the thread is started it will call the run() method of the MyClass instance instead of executing
its own run() method. The above example would print out the text "MyClass running ".

Extending Java Thread


The second way to create a thread is to create a new class that extends Thread, then override the run()
method and then to create an instance of that class. The run() method is what is executed by the thread
after you call start(). Here is an example of creating a Java Thread subclass:

public class MyClass extends Thread {


public void run(){
System.out.println("MyClass running");
}
}
To create and start the above thread:
MyClass t1 = new MyClass ();
T1.start();
When the run() method executes it will print out the text " MyClass running ".

Priority of a Thread
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling).

 public static int MIN_PRIORITY


26

 public static int NORM_PRIORITY


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 public static int MAX_PRIORITY

Example
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority
is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

DIFFERENCE BETWEEN PROCESS AND THREAD

S.N. Process Thread

1 Process is heavy weight or resource Thread is light weight, taking lesser resources
intensive. than a process.

2 Process switching needs interaction with Thread switching does not need to interact with
operating system. operating system.

3 In multiple processing environments, each All threads can share same set of open files,
process executes the same code but has its child processes.
own memory and file resources.

4 If one process is blocked, then no other While one thread is blocked and waiting, a
27

process can execute until the first process is second thread in the same task can run.
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

unblocked.

5 Multiple processes without using threads use Multiple threaded processes use fewer
more resources. resources.

6 In multiple processes each process operates One thread can read, write or change another
independently of the others. thread's data.

Advantages of Thread

 Threads minimize the context switching time.

 Use of threads provides concurrency within a process.

 Efficient communication.

 It is more economical to create and context switch threads.

 Threads allow utilization of multiprocessor architectures to a greater scale and efficiency.

DAEMON THREAD IN JAVA

Daemon thread in java is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.There are many java daemon threads running automatically e.g. gc, finalizer etc.You
can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java

o It provides services to user threads for background supporting tasks. It has no role in life than
to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.
28
Page

You might also like