Unit 3 Java Notes-II ML
Unit 3 Java Notes-II ML
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
� In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use
of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
� In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions
In java, the built-in classes used to handle exceptions have the following class hierarchy.
Exception Models in Java
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
In java, assume that, if we do not handle the exceptions in a program. In this case, when
an exception occurs in a particular function, then Java prints a exception message with
the help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at
the following code.
Example
When we execute the above code, it produce the following output for the value
a = 10 and b = 0.
In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.
In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Consider the following example code to illustrate try and catch blocks in Java.
Example
In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example
throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
� When a method throws an exception, we must put the calling statement of method in try-
catch block.
Let's look at the following example Java code to illustrate throws keyword.
Example
import [Link];
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner([Link]);
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
[Link]("Problem info: " + [Link]());
}
[Link]("End of the program");
}
}
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
�Only one finally block is allowed for each try block.
�Use of finally block is optional.
Let's look at the following example Java code to illustrate throws keyword.
Example
Built-in Exceptions in Java
The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package [Link].
Few built-in exceptions in Java are shown in the following image.
List of checked exceptions in Java
S.
No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object,
but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class Class , but the specified class object cannot be instantiated because it is an
interface or is an abstract class.
5 InterruptedException
6 NoSuchFieldException
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.
List of unchecked exceptions in Java
The following table shows the list of several unchecked exceptions.
S.
No. Exception Class with Description
1 ArithmeticException
2 ArrayIndexOutOfBoundsException
It handles the situations like 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.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
4 AssertionError
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the
specified monitor.
8 IllegalStateException
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.
10 IndexOutOfBoundsException
11 NegativeArraySizeException
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer,
but the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.
16 UnsupportedOperationException
The Java programming language allow us to create our own exception classes which are
basically subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in
Exception class.
We may create constructor in the user-defined exception class and pass a string to
Exception class constructor using super(). We can use getMessage() method to access
the string.
Let's look at the following Java code that illustrates the creation of user-defined
exception.
Example
import [Link];
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg); } }
class VoterList{
int age;
VoterList(int age){ [Link] = age; }
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
[Link]("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) { [Link]([Link]()); } }
public static void main(String args[]) {
Scanner input = new Scanner([Link]); [Link]("Enter your age in years: ");
int age = [Link](); VoterList person = new VoterList(age);
[Link]();
} }
Multithreading in java
Java I/O (Input/Output) is a collec on of classes and streams in the [Link] package that handle
reading data from sources (like files, keyboard, or network) and wri ng data to des na ons (like
files, console or sockets). It provides both byte and character streams to support all types of
data.
In java, the stream-based IO operations are performed using two separate streams input
stream and output stream.
The input stream is used for input operations, and the output stream is used for output
operations.
The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to
the console.
[Link]: standard output stream for console output operations.
[Link]: standard input stream for console input operations.
[Link]: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
Byte Stream
Character Stream
The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.
The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 void write(int n)
2 void write(byte[] b)
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.
In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream.
The unicode set is basically a type of character set where each character corresponds to a
specific numeric value within the given character set, and every programming language
has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used
for charater stream based output operations.
The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 int read()
It reads a chunk of charaters from the input stream and store them in its byte array,
cbuffer.
[Link]. Method with Description
5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed
('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.
6 boolean ready()
7 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes a string.
7 Writer append(char c)
10 void close()
It closes the output stream and also frees any resources connected with this output
stream.
Example
Example
3. Reading console input using Console class in java
Reading input data using the Console class is the most commonly used method. This class was introduced in
Java 1.6 version.
The Console class has defined in the [Link] package.
Consider the following example code to understand how to read console input using Console class.
Example
import [Link].*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = [Link]();
if(con != null) {
name = [Link]("Please enter your name : ");
[Link]("Hello, " + name + "!!");
}
else {
[Link]("Console not available.");
}
}
}
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name
a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
[Link]. Methods with Description
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application;
false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to
write to the file; false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the
named file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is
successfully deleted; false otherwise.
16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine
terminates.
17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent
directories; false otherwise.
otherwise.
21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the
operation succeeded; false otherwise.
22 String[] list()
It returns an array of strings containing names of all the files and directories in the
current directory.
24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in
the current directory.
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.
import [Link].*;
public class FileClassTest {
}
Let's look at the following java code to list all the files in a directory including the files present
in all its subdirectories.
Example
import [Link];
import [Link].*;
public class ListingFiles {
public static void main(String[] args) {
String path = null;
Scanner read = new Scanner([Link]);
[Link]("Enter the root directory name: ");
path = [Link]() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
[Link]("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while ([Link]("y")) {
printFiles(path);
[Link]("Do you want to open any sub-directory
(Y/N): ");
ch = [Link]().toLowerCase();
if ([Link]("y")) {
[Link]("Enter the sub-directory name: ");
path = path + "\\\\" + [Link]();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
[Link]("The sub-directory does not
exists!");
printLine();
int lastIndex = [Link]("\\");
path = [Link](0, lastIndex);
}
}
}
}
[Link]("***** Program Closed *****");
}
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.
FileInputStream - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the byte stream. The FileInputStream class provides a
method read() to read data from a file byte by byte.
FileOutputStream - It is a built-in class in java that allows writing data to a file. This
class has implemented based on the byte stream. The FileOutputStream class provides a
method write() to write data to a file byte by byte.
Let's look at the following example program that reads data from a file and writes the same to
another file using FileInoutStream and FileOutputStream classes.
Example
import [Link].*;
public class FileReadingTest {
try {
in = new FileInputStream("C:\\Raja\\[Link]");
out = new FileOutputStream("C:\\Raja\\[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing has been success!!!");
}
catch(Exception e){
[Link](e);
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
FileReader - It is a built-in class in java that allows reading data from a file. This class
has implemented based on the character stream. The FileReader class provides a
method read() to read data from a file character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.
Let's look at the following example program that reads data from a file and writes the same to
another file using FIleReader and FileWriter classes.
Example
import [Link].*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\[Link]");
out = new FileWriter("C:\\Raja\\[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
RandomAccessFile in Java
In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be
accessed randomly. The RandomAccessFile class has several methods used to move the cursor
position in a file.
A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
It creates a random access file stream to read from, and optionally to write to, the file specified
argument.
It creates a random access file stream to read from, and optionally to write to, a file with th
fileName.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.
1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
[Link]. Methods with Description
2 int read(byte[] b)
It reads byte of data from file upto [Link], -1 if end of file is reached.
It reads bytes initialising from offset position upto [Link] from the buffer.
4 boolean readBoolean()
5 byte readByte()
6 char readChar()
It reads a character value from file.
7 double readDouble()
8 float readFloat()
It reads a float value from file.
9 long readLong()
10 int readInt()
11 void readFully(byte[] b)
It reads bytes initialising from offset position upto [Link] from the buffer.
[Link]. Methods with Description
It reads bytes initialising from offset position upto [Link] from the buffer.
13 String readUTF()
It sets the file-pointer(cursor) measured from the beginning of the file, at which the
next read or write occurs.
15 long length()
16 void write(int b)
It writes the specified byte to the file from the current cursor position.
17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float,
and then writes that int value to the file as a four-byte quantity, high byte first.
18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in class
Double, and then writes that long value to the file as an eight-byte quantity, high byte
first.
import [Link].*;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
[Link]("Use of read() method : " + f_ref.read());
f_ref.seek(0);
// readByte() method :
[Link]("Use of readByte() : " + f_ref.readByte());
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
[Link]("Use of readChar() : " + f_ref.readChar());
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
[Link]("Use of readDouble() : " + f_ref.readDouble());
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
[Link]("Use of readFloat() : " + f_ref.readFloat());
f_ref.seek(0);
// Create array upto [Link]
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);