Unit_3
Unit_3
Bhavesh K. Hadiyal
HOD of Computer science
Department OMVVIM College
2022 - 23
Index
- Introduction to exception handling
- try, catch, finally, throw, throws
- Creating user defined Exception class
- Thread and its Life Cycle (Thread States)
- Thread Class and its methods
- Synchronization in Multiple Threads (Multithreading)
- Deamon Thread, Non-Deamon Thread
- Stream and its types (Input, Output, Character, Byte)
- File and RandomAccessFile Class
- Reading and Writing through Character
Stream Classes (FileReader, BufferedReader, FileWriter,
BufferedWriter)
- Reading and Writing through Byte Stream Classes
(InputStream, FileInputStream, DataInputStream,
OutputStream, FileOutputStream, DataOutputStream)
- StreamTokenizer Class
- Piped Streams,
- Bridge Classes: InputStreamReader and OutputStreamWriter
- ObjectInputStream, ObjectOutputStream
Exceptions in Java
Dictionary Meaning: Exception is an abnormal condition
An exception is an unexpected event that occurs during program execution.
It affects the flow of the program instructions which can cause the program to terminate
abnormally. In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
A. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions.
The compiler will not check these exceptions at compile time.
In simple words, if a program throws an unchecked or run-time exception, and even if we didn’t
handle or declare it, the program would not give a compilation error.
B. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
GO to index page
Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
Below is the list of important built-in exceptions in Java.
ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found.
FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
IOException: It is thrown when an input-output operation failed or interrupted
InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing,
and it is interrupted.
NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException: It is thrown when accessing a method that is not found.
NullPointerException: It is raised when referring to the members of a null object. (Null->nothing)
NumberFormatException: It is raised when method couldn’t convert string into a numeric format.
RuntimeException: This represents an exception that occurs during runtime.
StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is
either negative or greater than the size of the string
IllegalArgumentException : This exception will throw the error or error statement when the
method receives an argument which is not accurately fit to the given relation or condition. It
comes under the unchecked exception.
IllegalStateException : This exception will throw an error or error message when the method is not
accessed for the particular operation in the application. It comes under the unchecked exception.
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter marks of JAVA : ");
int $m = s.nextInt();
try
{
if($m<0 || $m > 100)
throw new MarksExceptionClass("Wrong MArks.");
else
System.out.println("Marks of JAVA is : " + $m);
}
catch(MarksExceptionClass obj)
{ System.out.println("Exception caught : " + obj); }
}
}
This would produce the following result:
Enter marks of JAVA :
123
Exception caught : javaapplication1.MarksExceptionClass: Wrong MArks.
GO to index page
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Typically, we can define threads as a sub process with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but they
act independently hence if there is an exception in threads that do not affect the working of other
threads despite them sharing the same memory.
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in
one of the shown states at any instant:
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated
The diagram shown below represents various states of a thread at any instant in time.
GO to index page
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)
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So, threads
are light-weight processes within a process.
Threads can be created by using two mechanisms :
Extending the Thread class
Implementing the Runnable Interface
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization?
The synchronization is mainly used to
If you start with at least two threads inside a program, there might be a chance when
multiple threads attempt to get to the same resource.
It can even create an unexpected outcome because of concurrency issues.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Process Synchronization: It means sharing system resources by processes in such a way that,
Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.
Thread Synchronization: It means that every access to data shared between threads is protected
so that when any thread starts operation on the shared data, no other thread is allowed access
until the first thread is done.
GO to index page
Daemon Thread and Non-Daemon
In Java, there are two types of threads:
Daemon Thread
User Thread (Non-Daemon )
Thread type is being checked (User thread or Daemon thread) by using isDaemon() method. It
returns true if it is daemon otherwise it returns false.
GO to index page
Stream in JAVA
What is stream?
In Java, “stream” essentially refers to an abstraction that is used to produce and consume
flow of sequential information.
A Stream is linked to a physical layer by java I/O system to make input and output operation
in java.
In general, a stream means continuous flow of data.
Based on the data they handle there are two types of streams
Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text
data only.
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of
8 bits. Using these you can store characters, videos, audios, images etc.
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. If end-of-file is reached before the desired number of byte has
been read than EOFException is thrown. It is a type of IOException.
Character Streams
Character stream is also defined by using two abstract classes
at the top of the hierarchy, they are Reader and Writer. These
two abstract classes have several concrete classes that handle
Unicode characters.
Reader classes: Abstract class that define character stream
input.
Writer classes: Abstract class that define character stream
output.
Some important Character stream classes:
PipedOutputStream Class
The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of the
PipedOutputStream class.
Constructor:
PipedOutputStream() : creates a PipedOutputStream, that it is not connected.
PipedOutputStream(PipedOutputStream inStream) : creates a PipedOutputStream, that it is
connected to PipedInputStream – ‘inStream’.
Methods:
write() : java.io.PipedOutputStream.write(int byte) writes a specified byte to the Piped Output
Stream.
GO to index page
Constructor:
PipedInputStream() : creates a PipedInputStream, that it is not connected.
PipedInputStream(int pSize) : creates a PipedInputStream, that it is not connected with specified
pipe size.
PipedInputStream(PipedOutputStream outStream) : creates a PipedInputStream, that it is
connected to PipedOutputStream – ‘outStream’.
PipedInputStream(PipedOutputStream outStream, int pSize) : creates a Piped Input Stream that is
connected to Piped Output Stream with the specified pipe size.
Methods:
int read(): Reads the next byte of data from this piped input stream.The value byte is returned as
an int in the range 0 to 255. This method blocks until input data is available, the end of the stream
is detected, or an exception is thrown.
Bridge classes in JAVA
Methods of InputStreamReader
read() - reads a single character from the reader
read(char[] array) - reads the characters from the reader and stores in the specified array
read(char[] array, int start, int length) - reads the number of characters equal to length from the
reader and stores in the specified array starting from the start
getEncoding() method can be used to get the type of encoding that is used to store data in the
input stream.
close() : To close the input stream reader, we can use the close() method. Once
the close() method is called, we cannot use the reader to read the data.
Methods of OutputStreamWriter
write() - writes a single character to the writer
write(char[] array) - writes the characters from the specified array to the writer
write(String data) - writes the specified string to the writer
getEncoding() method can be used to get the type of encoding that is used to write data to the
output stream.
close() : To close the output stream writer, we can use the close() method. Once
the close() method is called, we cannot use the writer to write the data.
GO to index page
ObjectInputStream & ObjectOutputStream
We use object streams to read and write Java objects in binary
format. ObjectInputStream and ObjectOutputStream are the main object stream classes provided
by the Java File I/O API.
Basically, the ObjectOutputStream and ObjectOutputStream encodes Java objects using the class
name and object values. And, hence generates corresponding streams. This process is known as
serialization.
Methods of ObjectInputStream
The ObjectInputStream class provides implementations of different methods present in
the InputStream class.
read() Method
read() - reads a byte of data from the input stream
readBoolean() - reads data in boolean form
readChar() - reads data in character form
readInt() - reads data in integer form
readObject() - reads the object from the input stream
available() - returns the available number of bytes in the input stream
mark() - marks the position in input stream up to which data has been read
reset() - returns the control to the point in the input stream where the mark was set.
skipBytes() - skips and discards the specified bytes from the input stream
close() - closes the object input stream
Methods of ObjectOutputStream
The ObjectOutputStream class provides implementations for different methods present in
the OutputStream class.
write() Method
write() - writes a byte of data to the output stream
writeBoolean() - writes data in boolean form
writeChar() - writes data in character form
writeInt() - writes data in integer form
writeObject() - writes object to the output stream
flush() - clears all the data from the output stream
drain() - puts all the buffered data in the output stream
close() - closes the output stream
GO to index page