Java Unit III
Java Unit III
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 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
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.
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
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
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
}
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
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.
Example
import java.io.*;
public class className {
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 {
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
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 {
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
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 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:
STREAM
A stream can be defined as a sequence of data. There are two kinds of Streams −
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
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 {
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();
}
}
}
}
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 {
FileReader in = null;
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
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();
}
}
}
}
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 {
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
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.
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 −
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 −
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.
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 −
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 −
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.
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
import java.io.*;
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
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();
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 is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
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.
Constructor Description
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
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()
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 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:
Constructor Description
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
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
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:
BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.
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{
JAVA - MULTITHREADING
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in
the same program.
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.
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.
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 −
As a second step, you will instantiate a Thread object using the following constructor −
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
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.
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 ".
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).
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();
}
}
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
Efficient communication.
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.
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