Java Unit Iii-1
Java Unit Iii-1
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.
1Page
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.
• 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
2Page
catch block alone. It can be followed by finally block later.
CATCHING EXCEPTIONS
A method catches an exception using a combination of thetry and catch keywords. A try/catch block
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.
3Page
Example public class MyClass { public static void
main(String[ ] args) {
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
}
4Page
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
using the throw keyword.
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.
}
// Remainder of class definition
}
The following method declares that it throws a RemoteException −
Example
5Page
import java.io.*; public
class className {
// Method implementation
}
// Remainder of class definition
}
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
matter what happens in the protected code.
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
Output
6Page
public class ExcepTest {
• 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
7Page
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.
9Page
import java.io.*; public class
CopyFile {
int c; while
((c = in.read()) != -1) {
out.write(c);
}
}finally { if (in !=
null) {
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
1Page
in.close();
} if (out !=
null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
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
used to perform input and output of
Java Byte streams are 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there are
to character streams but the most
many classes related 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
int c;
while ((c = in.read()) !
= -1) {
out.write(c);
}
}finally { if
(in != null) {
in.close();
} if (out !=
null) {
out.close();
}
FileReader in = null;
} let's have a file input.txt
Now 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 −
12
Page
• 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();
}
}
}
}
13
Page
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
ee
q
q
As described earlier, a stream can be defined as a sequence of data. TheInputStream 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.
FileInputStream
14
Page
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.
15 FileOutputStream
Page
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.
Example
16 import java.io.*;
Page
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.
Constructor Description
Method Description
17
Page
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.
void close() It closes the input stream and releases any of the system resources
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 markSupported() It tests for the input stream to support the mark and reset methods.
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;
18 while((i=bin.read())!=-1){
Page
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
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:
19
Page
Java BufferedOutputStream class declaration
Constructor Description
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, It write the bytes from the specified byte-input stream into a specified
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.
20
Page
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
Console
Scanner
DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
21
Page
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
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
22 application.
Page
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.
• 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.
23
Page
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 −
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
5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
25
Page
Causes the currently running thread to yield to any other threads of the same priority that
are waiting to be scheduled.
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:
Inside run( ), we will define the code that constitutes the new thread. Example:
public class MyClass implements Runnable
{ public void
run()
{
System.out.println("MyClass running");
}
}
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).
When the thread is started it will call the run() method of the MyClass instance instead of executing
26 its own run() method. The above example would print out the text "MyClass running ".
Page
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:
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).
}
27 public static void main(String args[]){
Page
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
operating system. with 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
process can execute until the first process is second thread in the same task can run.
unblocked.
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.
28
Page
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.
29
Page