Professional Documents
Culture Documents
Lecture Notes
Unit – III
Exception handling, Stream based I/O
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and catch, multiple
catch clauses, nested try statements, throw, throws and finally, built-in exceptions, creating own exception
subclasses.
Stream based I/O (java.io) – The Stream Classes-Byte streams and Character streams, reading console Input
and Writing Console Output, File class, Reading and Writing Files, Random access file operations, The
Console class, Serialization, Enumerations, Autoboxing, Generics.
F:\JAVA>java Error
Error: Main method not found in class Error, please define the main method as:
public static void main(String[] args)
Run – time errors are not detected by the java compiler. They are detected by the JVM, only at runtime.
3. Logical errors: These errors represent error in the logic of the program. The programmer might be
using a wrong formula or the design of the program itself is wrong. Logical errors are not detected
either by a java compiler or JVM. The programmer is only responsible for them.
E.g.:
//logical error
class Error
{
public static void main(String args[])
{
double sal=5000.00;
sal = sal * 15/100; // wrong. Use: sal+=sal*15/100;
System.out.println("Incremented salary= "+sal);
}
}
F:\JAVA>java Error
Incremented salary= 750.0
By comparing the output of a program with manually calculated results, a programmer can guess the
presence of a logical error.
2
The classification of exceptions – exception hierarchy:
If the source code is syntactically incorrect, java compiler reports compilation errors. During program
execution, if run – time environment rules are violated, JVM reports run – time errors known as exceptions.
Object oriented representation of an abnormal event occurred during program execution is known as an
exception. When an exception is raised program gets terminated abnormally. Abnormal termination of the
program causes the following problems.
1. End user loses previous work and data.
2. End user doesn’t have proper information about what went wrong.
3. Any resources allocated to the application cannot be resubmitted.
Exception is thrown by the JVM and is caught by the handler. Pre – created exception classes are known as
standard exceptions. Our own created exceptions are known as user defined exceptions. In java, exception
is an object that is an instance of some sub class of java.lang.Throwable. java.lang.Throwable class is the
super class of all exceptions. It has two main sub classes:
1. Error
2. Exception
The differences between error and exception:
1. Error type exceptions are thrown due the problem occurred inside JVM logic, like
If there is no memory in JSA to create, new stack frame to execute method, JVM process is
killed by throwing Error type exception “java.lang.StackOverFlowError”.
If there is no memory HA to create, new object, then JVM process is killed by throwing Error
type exception “java.lang.OutOfMemoryError”.
Exception type exceptions are thrown due to the problem that occurred in java program logic execution
like,
If we divide an integer number with zero, then JVM terminates the program execution by throwing
Exception type exception “java.lang.ArithmeticException”.
2. We cannot catch Error type exception, because Error type exception is not thrown in our application,
and once this Error type exception is thrown JVM is terminated.
We can catch Exception type exceptions, because Exception type exception is thrown in our
application, and more over JVM is not directly terminated. JVM is terminated only if the thrown
exception is not caught.
The following diagram shows “java.lang” package exception classes hierarchy.
3
Checked exceptions and unchecked exceptions:
java.lang.Exception class has 2 kinds of sub classes:
1. Checked exception classes: The exceptions that are checked at compilation time by the java compiler
are called ‘checked exceptions’. The checked exceptions are recognized by the compiler. In the
exception hierarchy, except the RuntimeException and its sub classes all other sub classes of Exception
class are called checked exceptions.
E.g.: FileNotFoundException, IOException, InterruptedException etc.
Let us now consider a statement.
public static void main(String a[])throws IOException
Here, IOException is an example for checked exception. So we threw it out of main() method without
handling it. We can also handle it. Suppose, we are not handling it and not even throwing it, then the
java compiler will give an error.
2. Unchecked exception classes: The exceptions that are checked by the JVM are called ‘unchecked
exceptions’. In the exception hierarchy, the RuntimeException and its sub classes are called as
unchecked exceptions.
E.g.: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException etc.
//An exception example
class Ex
{
public static void main(String args[])
{
System.out.println("open the files");
int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
System.out.println("close the files");
}
}
F:\JAVA>java Ex
open the files
n= 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Ex.main(exception.java:10)
Please observe the output of this program. When we passed 3 command line arguments, then the
program executed without any problem. But when we run the program without passing any arguments,
then n value become zero. So there will be an exception at runtime. In this case, JVM displays
4
exception details and then terminates the program abnormally. The sub sequent statements in the
program are not executed. When there is an exception, the files may not be closed, or the threads may
abnormally terminate or the memory may not be freed properly.
Exception handling:
The process of catching the exception for converting JVM given exception message to programmer
understandable message or for stopping abnormal termination of the program is called exception handling.
For this, we should perform the following steps:
The programmer should observe the statements in his program where they may be a possibility of
exceptions. Such statements should be written inside a try block. A try block looks like as follows:
try
{
statements;
}
The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. When JVM understands that there is an exception, it stores the exception details in an
exception stack and then jumps into a catch block.
The programmer should write the catch block where he should display the exception details to the
user. This helps the user to understand that there is some error in the program. The programmer should
also display a message regarding what can be done to avoid this error. Catch block looks like as
follows:
catch(Exception class ref)
{
Statements;
}
The reference ref is automatically refer to the exception stack where the details of the exception are
available. So, we can display the exception details using any one of the following ways:
1. Using print() or println() methods, such as System.out.println(ref);
2. Using printStackTrace() method of Throwable class, which fetches exception details from
the exception stack and displays them.
Lastly, the programmer should perform cleanup operations like closing the files and terminating the
threads. The programmer should write this code in the finally block like as follows:
finally
{
Statements;
}
The specialty of the finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not. This ensures that all the opened files are properly
closed and all the running threads are properly terminated.
Performing the above tasks is called ‘exception handling’.
E.g.:
//Exception handling using try, catch and finally blocks
class Ex
{
public static void main(String args[])
{
5
try
{
System.out.println("open the files");
int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
System.out.println("please pass data while running this program");
}
finally
{
//close the files
System.out.println("close files");
}
}
}
F:\JAVA>java Ex
open the files
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program
close files
try:
It is a keyword used to create a block of statements. In our java application what ever code is doubtful for
raising exceptions, that code is placed in the try block. A try block looks like as follows:
try
{
statements;
}
The greatness of try block is that even if some exception arises inside it, the program will not be terminated.
When JVM understands that there is an exception, it stores the exception details in an exception stack and
then jumps into a catch block.
catch:
It is a keyword used to create a block of statements. Catch block is a method block. In the catch block we
write exception handling code. So, catch block is the exception handler. The programmer should write the
6
catch block where he should display the exception details to the user. This helps the user to understand that
there is some error in the program. The programmer should also display a message regarding what can be
done to avoid this error. Catch block looks like as follows:
catch(Exception class ref)
{
Statements;
}
The reference ref is automatically refer to the exception stack where the details of the exception are available.
So, we can display the exception details using any one of the following ways:
1. Using print() or println() methods, such as System.out.println(ref);
2. Using printStackTrace() method of Throwable class, which fetches exception details from the
exception stack and displays them.
Between try block and catch block no other statement is allowed.
One try block can have any number of catch blocks.
If exception is not raised in the try block, control never goes to catch block.
If exception is raised in the try block, try block gets terminated instead of program getting terminated.
JVM calibrates the kind of abnormal event, instantiates the appropriate exception class object and
throws it. Catch block is implicitly called.
To the catch block the reference of the exception object is supplied as argument. Application user can
use that reference in the catch block to find where about us and what about us of the exception.
E.g.:
//Exception handling using try, catch and finally blocks
class Ex
{
public static void main(String args[])
{
try
{
System.out.println("open the files");
int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
System.out.println("please pass data while running this program");
}
}
}
7
O/P: F:\JAVA>javac exception1.java
F:\JAVA>java Ex 1 2 3
open the files
n= 3
a= 15
F:\JAVA>java Ex
open the files
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program
throw:
It is a keyword used to throw exception explicitly. We need to create the exception object and throw it.
Generally JVM creates the exception object and throws it.
Syntax:
someexception e=new someexception();
throw e;
E.g.:
//using throw
class Throw
{
static void demo()
{
try
{
System.out.println("Inside demo()");
throw new NullPointerException("Exception data");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class ThrowDemo
{
public static void main(String args[])
{
Throw.demo();
}
}
8
F:\JAVA>java ThrowDemo
Inside demo()
java.lang.NullPointerException: Exception data
throws:
This keyword is used to pass exceptions to the next level instead of handling it in a method. This keyword is
associated with method declaration. For a method we can associate any number of exceptions with throws
clause. It is associated with a method declaration means the method has doubtful code but not handled it. It is
the responsibility of the calling method to handle the exceptions.
Syntax:
Return type mehod() throws exception1, exception2, exception3
{
//body of the method
}
Even if the programmer is not handling runtime exceptions, the java compiler will not give any error related
to runtime exceptions. But the rule is that the programmer should handle checked exceptions. In case the
programmer does not want to handle the checked exceptions; he should throw them out using throws clause.
Otherwise, there will be an error flagged by java compiler.
E.g.:
//Not handling the exception
import java.io.*;
class Sample
{
private String name;
void accept()
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.println("enter name: ");
name=br.readLine();
}
void display()
{
System.out.println("Name: "+name);
}
}
class Ex1
{
public static void main(String args[])
{
Sample s=new Sample();
s.accept();
s.display();
}
}
9
O/P: F:\JAVA>javac throws.java
throws.java:11: error: unreported exception IOException; must be caught or declared to be thrown
name=br.readLine();
^
1 error
In this program, the java compiler expects the programmer to handle the IOException using try and catch
blocks; else, he should throw out the IOException without handling it. But the programmer is not performing
either. So there is a compile time error displayed.
F:\JAVA>java Ex1
enter name:
vbr
Name: vbr
finally:
It is a keyword used to create a block of statements that execute definitely in both the cases i.e. in exception
generated case and no generated case also. It cannot be written individually. It succeeds either try block or
catch block.
10
Syntax: finally
{
Statements;
}
E.g.:
//Exception handling using try, catch and finally blocks
class Ex
{
public static void main(String args[])
{
try
{
System.out.println("open the files");
int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
System.out.println("please pass data while running this program");
}
finally
{
//close the files
System.out.println("close files");
}
}
}
F:\JAVA>java Ex
open the files
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program
close files
Rethrowing Exceptions:
11
When an exception occurs in a try block, it is caught by a catch block. This means that the thrown exception
is available to the catch block. The following code shows how to re-throw the same exception out from the
catch block.
try
{
throw exception;
}
catch(Exception obj)
{
throw exception; //re-throw the exception out
}
Suppose there are two classes A and B. If an exception occurs in A, we want to display some message to the
user and then we want to re-throw it. This re-thrown exception can be caught in class B where it can be
handled. Hence re-throwing exceptions is useful especially when the programmer wants to propagate the
exception details to another class. In this case the exception details are sent from class A to class B where
some appropriate action may be performed.
E.g.:
//rethrowing an exception
class A
{
void method1()
{
try
{
//take a string with 5 chars. Their index is from 0 to 4
String str="Hello";
//exception is thrown in below statement because there is no index with value 5
char ch=str.charAt(5);
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println("Please see the index is within the range");
throw sie; //rethrow the exception
}
}
}
class B
{
public static void main(String args[])
{
//create an object to A and call method1()
A a=new A();
try
{
a.method1();
}
12
//the rethrown exception is caught by the below catch block
catch(StringIndexOutOfBoundsException sie)
{
System.out.println("I caught rethrown exception");
}
}
}
Types of Exceptions:
Following are the exceptions available in java:
1. Built – in exceptions
2. User – defined exceptions
1. Built – in Exceptions:
Built – in exceptions are the exceptions which are available in java. These exceptions are suitable
certain error situations. The following table lists the important built – in exceptions:
13
java.lang.Exception or its sub class. The following steps are followed in creation of user – defined
exceptions:
The user should create an exception class as a subclass to Exception class. Since all exceptions
are subclasses of Exception class, the user should make his class a subclass to it. This is done
as:
class MyException extends Exception
The user can write a default constructor in his own exception class. He can use it, in case he
does not want to store any exception details. If the user does not want to create an empty object
to his exception class, he can eliminate writing the default constructor.
MyException() {}
The user can create a parameterized constructor with a string as a parameter. He can use this
to store exception details. He can call super class (Exception) constructor from this and send
the string there.
MyException(String str)
{
Super(str);
}
When the user wants to raise his own exception, he should create an object to his exception
class and throw it using throw clause, as:
MyEXception me=new MyException(“Exception details”);
throw me;
E.g.:
//user defined exception
//to throw whenever balance amount is below Rs. 1000
class MyException extends Exception
{
//store account information
private static int acno[]={1001,1002,1003,1004,1005};
private static String name[]={"vijay","balaji","sahithi","ajay","nandini"};
private static double bal[]={100.00,100.00,5600.50,1999.00,11000.00};
//default constructor
MyException()
{
}
//parameterized constructor
MyException(String str)
{
super(str);
}
public static void main(String args[])
{
try
{
//display the heading for the table
System.out.println("ACCNO"+"\t"+"CUSTOMER"+"\t"+"BALANCE");
//display actual account information
14
for(int i=0;i<5;i++)
{
System.out.println(acno[i]+"\t"+name[i]+"\t"+"\t"+bal[i]);
//display own exception if balance<1000
if(bal[i]<1000)
{
MyException me=new MyException("Balance amount is less");
throw me;
}
}
}
catch(MyException me)
{
me.printStackTrace();
}
}
}
F:\JAVA>java MyException
ACCNO CUSTOMER BALANCE
1001 vijay 100.0
MyException: Balance amount is less at MyException.main(ownexception.java:31)
catch(ArithmeticException ae)
15
{
//display the exception details
System.out.println(ae);
System.out.println("please pass data while running this program");
}
catch(ArrayIndexOutOfBoundsException aie)
{
//display the exception details
System.out.println(aie);
System.out.println("please see that the array index is within the range");
}
}
}
F:\JAVA>java MultipleCatch
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program
Streams:
16
A stream carries data just as a water pipe carries water from one place to another. Streams can be categorized
as input streams and output streams. Input streams are the streams which receive or read data while output
streams are the streams which send or write data. All the streams are represented by classes in java.io (input
– output) package.
Now, let us see how a stream works. We know an input stream reads data. So, to read data from keyboard, we
can attach the keyboard to an input stream, so that the stream can read the data typed on the keyboard.
DataInputStream dis=new DataInputStream(System.in);
In the above statement, we are attaching the keyboard to DataInputStream object. The keyboard is represented
by System.in. Now, DataInputStream object can read data coming from the keyboard. Here, System is a class
and in is a field in System class. In fact, the System class has the following 3 fields:
System.in: represents InputStream object. This object represents the standard input device, that is
keyboard by default.
System.out: represents PrintStream object. This object by default represents the standard output
device, which is monitor.
System.err: represents PrintStream object. This object by default represents the standard output
device, which is monitor.
Types of java streams:
In java we are allowed to send data through streams only, either in the format of bytes or characters. Hence,
based on the type of data passed, streams are divided into two types:
Byte streams and character streams:
Java defines two types of streams: byte and character. Byte streams provide a convenient means for handling
input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character
streams provide a convenient means for handling input and output of characters.
Byte stream classes:
Byte streams represent data in the form of individual bytes. If a class name ends with the word ‘stream’, then
it comes under byte streams. Byte streams are used to handle any characters (text), images, audio, and video
files. For example, to store an image file (.jpg or .gif), we should go for a byte stream. Byte streams are defined
by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of
these abstract classes has several concrete subclasses that handle the differences between various devices,
such as disk files, network connections, and even memory buffers.
The abstract classes InputStream and OutputStream define several key methods that the other stream
classes implement. Two of the most important are read() and write(), which respectively, read and write bytes
of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden
by derived classes. The important classws of byte streams are shown in the following diagrams.
Types of streams:
Generally streams are divided into two types based on data flow direction.
InputStream: The stream that allows data to come into the java application from the persistent media is called
input stream.
OutputStream: The stream that allows data to send out from the java application to be stored into the
persistent media is called output stream. Basically input streams are used to read data from a persistent media
and output streams are used to write or store data in persistent media from a java application.
FileInputStream and FileOutputStream: These classes are used to read and write data as bytes from file.
Basically, these two streams are used as basic data source and destination for other streams.
DataInputStream and DataOutputStream: These classes are used to read and write data as primitive data.
Basically, these two streams are used to add capability to another input stream and output stream inorder to
read and write data as primitive types.
ObjectInputStream and ObjectOutputStream: These classes are used to read and write data as object.
Basically, these two streams perform object serialization and deserialization.
BufferedInputStream and BufferedOutputStream: These classes are used to read and write data as buffers.
Basically, these two streams are used to improve reading and writing performance of other streams.
SequenceInputStream: This class is used to read data from multiple Inputstreams sequentially.
PrintStream: This class is used to write data.
FileReader and FileWriter: These two classes are used to read and write data from a file as characters. It is
recommended to use FileReader and FileWriter classes to read data from text file where as FileInputStream
and FileOutputStream classes are only recommended to read and write image files.
BufferedReader and BufferedWriter: These two classes are used to improve reading and writing capability
of other input and output stream.
InputStreamReader and OutputStreamWriter: An InputStreamReader is a bridge from byte streams to
character streams. It reads bytes and decodes them into characters using a specified charset.
An OutputStreamWriter is a bridge from character streams to byte streams. Characters written to it are encoded
into bytes using a specified charset.
Binary input/output:
18
FileInputStream and FileOutputStream: These classes are used to read and write data as bytes from file.
Basically, these two streams are used as basic data source and destination for other streams.
FileOutputStream: This class is used to write data to a file.
Constructors:
1. FileOutputStream(String name) throws FileNotFoundException
2. FileOutputStream(File f) throws FileNotFoundException
3. FileOutputStream(String name, boolean append) throws FileNotFoundException
4. FileOutputStream(File f, boolean append) throws FileNotFoundException
Creating a file using FileOutputStream:
FileOutputStream class belongs to byte stream and stores data in the form of individual bytes. It can be used
to create text files. The following steps are to be followed to create a text file that stores some characters.
1. First os all, we should read data from the keyboard. For this purpose, we should attach keyboard to
some input stream class. The code for using DataInputStream class for reading from the keyboard is
as:
DataInputStream dis=new DataInputStream(System.in);
Here, System.in represents the keyboard which is linked with DataInputStream class object dis.
2. Now, attach a file where the data is to be stored to some output stream. Here, we take the help of
FileOutputStream which can send data to the file. Attaching the file myfile.txt to
FileOutputStream can be done as:
FileOutputStream fout=new FileOutputStream(“myfile.txt”);
3. The next step to read data from DataInputStream and write it into FileOutputStream and write it
into FileOutputStream. It means read data from dis object and write it into fout object, as shown
here:
char ch=(char)dis.read();
fout.write(ch);
Finally, any file should be closed after performing input or output operations on it, else the data of
the file may be corrupted. Closing the file is done by closing the associated streams. For example,
fout.close(); will close the FileOutputStream.
E.g.:
//creating a text file using FileOutputStream
import java.io.*;
class FileCreate
{
public static void main(String args[])throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);
//read characters from dis into ch. Then write them into fout.
//repeat this as long as the read character is not @
19
while((ch=(char)dis.read())!='@')
fout.write(ch);
In this program, we read data from the keyboard and write it into myfile315.txt. This program accepts data
from the keyboard till the user types @ when he does not want to continue. To view the contents of
myfile315.txt, we can use type command in DOS or cat command in UNIX.
20
//attach FileOutputStream to BufferedOutputStream
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
//read characters from dis into ch. Then write them into bout.
//repeat this as long as the read character is not @
while((ch=(char)dis.read())!='@')
bout.write(ch);
F:\JAVA>java FileCreate
Enter text (@ at the end):
this is II mca
this is necg
@
F:\JAVA>type myfile.txt
this is my file line four
this is my file line five
this is my file line six
this is my file line seven
this is my last line
this is vbr
this is mca
this is II mca
this is necg
21
This will enable us to read data from the file. Then, to read data from the file, we should read data from the
FileInputStream as:
ch=fin.read();
Then, we should attach the monitor to output stream, example PrintStream, so that the output stream
will send data to the monitor. For displaying the data, we can use System.out which is nothing but
PrintStream object.
System.out.print(ch);
E.g.:
//reading text file using FileInputStream
import java.io.*;
class FileRead
{
public static void main(String args[])throws IOException
{
//attach the file to FileInputStream
FileInputStream fin=new FileInputStream("myfile.txt");
F:\JAVA>java FileRead
File contents:
this is my file line four
this is my file line five
this is my file line six
this is my file line seven
this is my last line
this is vbr
this is mca
this is II mca
this is necg
The above program works with myfile.txt only. To make this program work with any file, we should accept
the file name from the keyboard. For this purpose, create BufferedReader object as:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
22
Here, the keyboard (System.in) is attached to InputStreamReader which is attached to BufferedReader. So if
we read data from the BufferedReader, then that is actually read from the keyboard. Using readLine()
method of the BufferedReader class we can read the file name from the keyboard as:
String fname=br.readLine();
The file name should be attached to FileInputStream for reading data as:
FileInputStream fin=new FileInputStream(fname);
E.g.:
//reading data from any text file
import java.io.*;
class FileRead
{
public static void main(String args[])throws IOException
{
//to accept file name from keyboard
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
String fname=br.readLine();
23
Enter file name: myfile315.txt
File contents:
this is necg
DataInputStream and DataOutputStream:
These classes are used to read and write the data as primitive type from the underlying input stream and output
stream. These classes have special methods to perform reading and writing operation as primitive data type.
DataInputStream: It is a sub class of FilterInputStream and DataInput interface. It implements following
methods from the DataInput interface for reading bytes from a BinaryInputStream and convert them into
corresponding java primitive data types.
DataOutputStream: It is a sub class of FilterOutputStream and DataOutput interface. It implements
following methods from the DataOutput interface for converting data from any of the java primitive data types
to a stream of bytes and writing these bytes to a BinaryOutputStream.
To read data as primitive data types using readxxx() method, the data must be written to the file as primitive
types using writexxx() method.
E.g.:
//reading and writing primitive data
import java.io.*;
class ReadWrite
{
public static void main(String args[])throws IOException
{
//File primitive=new File(prim.dat);
FileOutputStream fos=new FileOutputStream("prim.txt");
DataOutputStream dos=new DataOutputStream(fos);
//write primitive data to the "prim.txt" file
dos.writeInt(1999);
dos.writeDouble(375.12);
dos.writeBoolean(false);
dos.writeChar('V');
dos.close();
fos.close();
//read data from the "prim.txt" file
FileInputStream fis=new FileInputStream("prim.txt");
DataInputStream dis=new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}
O/P: F:\JAVA>javac prim.java
F:\JAVA>java ReadWrite
1999
375.12
24
false
V
Text input/output:
FileReader and FileWriter:
These two classes are used to read and write data from a file as characters. It is recommended to use FileReader
and FileWriter classes to read data from text file where as FileInputStream and FileOutputStream classes are
only recommended to read and write image files.
FileReader: FileReader is useful to read data in the form of characters from a text file.
Constructors:
1. FileReader(String name)
2. FileReader(File f)
Methods of FileReader;
1. int read()
It attempts to read next character from the file and returns its Unicode value. If the next character is not
available, then we will get -1 i.e. it returns -1.
2. int read(char[] ch)
It attempts to read enough characters from the file into the char[] array and returns the number of characters
copied.
3. void close()
E.g.:
//Reading data from a file using FileReader
import java.io.*;
class ReadFile
{
public static void main(String args[])throws IOException
{
int ch;
//check if file exists or not
FileReader fr=null;
//check if file exists or not
try
{
fr=new FileReader("myfile.txt");
}
catch(FileNotFoundException fe)
{
System.out.println("File not found");
return;
}
//read from FileReader till the end of file
while((ch=fr.read())!=-1)
System.out.print((char)ch);
//close the file
fr.close();
}
25
}
O/P: F:\JAVA>javac filereader.java
F:\JAVA>java ReadFile
this is vbr
FileWriter: FileWriter is useful to create a file by writing characters into it.
Constructors:
1. FileWriter(String name)
2. FileWriter(File f)
3. FileWriter(String name, boolean append)
4. FileWriter(File f, boolean append)
Methods:
1. write(int i): To write a single character to the file.
2. write(char[] ch): To write an array of characters to the file.
3. write(String s): To write a string to the file.
4. flush(): To give guarantee that the last character of the data is also added to the file.
5. close(): Close the file.
E.g.:
//creating a file using FileWriter
import java.io.*;
class CreateFile
{
public static void main(String args[])throws IOException
{
String str="This is a book on java."+"\n I am learner of java.";
//attach file to FileWriter
FileWriter fw=new FileWriter("new.txt");
//read characterwise from string and write it into FileWriter
for(int i=0;i<str.length();i++)
fw.write(str.charAt(i));
//close the file
fw.close();
}
}
O/P: F:\JAVA>javac filewriter.java
F:\JAVA>java CreateFile
F:\JAVA>type new.txt
This is a book on java.
I am learner of java.
BufferedReader and BufferedWriter:
These two classes are used to improve reading and writing capability of other input and output stream.
BufferedWriter: We can use the BufferedWriter to write character data to the file.
Constructors:
1. BufferedWriter bw=new BufferedWriter(writer w);
2. BufferedWriter bw=new BufferedWriter(writer w, int buffersize);
BufferedWriter never communicates directly with the file.
BufferedWriter bw=new BufferedWriter(new FileWriter(“newfile1.txt”));
26
Methods:
1. write(int i)
2. write(char[] ch)
3. write(String s)
4. flush()
5. close()
6. newLine(): To insert line separator.
E.g.:
import java.io.*;
class Buffer
{
public static void main(String args[])throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("new1.txt"));
bw.write(68);
bw.newLine();
char[] ch={'a','b','c'};
bw.write(ch);
bw.newLine();
bw.write("vbr");
bw.newLine();
bw.flush();
bw.close();
}
}
O/P: F:\JAVA>javac buff.java
F:\JAVA>java Buffer
F:\JAVA>type new1.txt
D
abc
vbr
BufferedReader: We can use the BufferedReader to read data from the file. The main advantage of
BufferedReader over the FileReader is we can read the data line by line instead of character by character.
Constructors:
1. BufferedReader br=new BufferedReader(Reader r);
2. BufferedReader br=new BufferedReader(Reader r, int buffersize);;
Methods:
1. int read()
2. int read(char[] c)
3. void close();
4. String readLine()
E.g.:
import java.io.*;
class Buffer
{
public static void main(String args[])throws IOException
27
{
BufferedReader br=new BufferedReader(new FileReader("new1.txt"));
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
line=br.readLine();
}
br.close();
}
}
O/P: F:\JAVA>javac buff.java
F:\JAVA>java Buffer
D
abc
vbr
28
E.g.:
import java.io.*;
class FileProp
{
public static void main(String a[])
{
String fname=a[0];
File f=new File(fname);
System.out.println("File name:"+f.getName());
System.out.println("path:"+f.getPath());
System.out.println("Absolute path:"+f.getAbsolutePath());
System.out.println("parent:"+f.getParent());
System.out.println("Exists:"+f.exists());
if(f.exists())
{
System.out.println("is writeable:"+f.canWrite());
System.out.println("is readable:"+f.canRead());
System.out.println("is a directory:"+f.isDirectory());
System.out.println("FIle size in bytes:"+f.length());
}
}
}
File copy: sometimes we need to copy the entire data of a text file into another text file. Streams are useful
in this case. How to use streams for copying file content to another file, we can use the following logic:
1. For reading data from the input file, attach it to FileInputStream.
2. For writing data into the output file, which is to be created, attach it to FileOutputStream.
3. Now, read data from FileInputStream and write into FileOutputStream. This means, the data is read
from the input file and send to output file.
E.g.:
//copying a file contents as another file
import java.io.*;
class CopyFile
{
public static void main(String args[])throws IOException
{
int ch;
29
while((ch=fin.read())!=-1)
fout.write(ch);
F:\JAVA>type filecpy1.java
//copying a file contents as another file
import java.io.*;
class CopyFile
{
public static void main(String args[])throws IOException
{
int ch;
30
with java’s primitive data types. The RandomAccessFile class is a very useful class for file handling. The
constructor of these classes is the following:
RandomAccessFile(String filename, String mode);
RandomAccessFile(File f, String mode);
Thus, RandomAccessFile objects can be created either from a string containing the file name or from a File
object. The mode represents the type of access to the file, for example, ‘r’ for read and ‘rw’ for read and write.
There are two other modes, namely, ‘rws’ and ‘rwd’, ‘rws’ opens the file as read and write and stores the
updations made on the file data or metadata in the synchronized way. Whereas, ‘rwd’ deals with the file data
but not the meta data. Here meta data refers to the data about the files. The method seek() points the file pointer
to the location specified by number. RandomAccessFile throws an IOException if an I/O error has occurred.
E.g.:
//writing and reading with random access
import java.io.*;
class Random
{
public static void main(String args[])throws IOException
{
RandomAccessFile file=null;
file=new RandomAccessFile("random.txt","rw");
file.writeChar('V');
file.writeInt(2012);
file.writeDouble(3.14);
31
Generics
When we create a class with an instance variable to store an integer object, it can be used to store Integer type
data only. We can not use that instance variable to store Float class object or a String type object. This becomes
a limitation. Let us take a class;
class A
{
Integer x;
}
Now, it is not possible to store a String or Float in this class A, since the instance variable x is of type Integer
and it can store only an Integer object. To store String or Float type value in class A, we can rewrite the class,
as:
class A class A
{ {
String x; (or) Float x;
} }
So, to store different types of data into a class, we have to write the same class again and again by changing
the data type of the variables. This can be avoided if we use a ‘generic class’.
Generic class: A generic class represents a class that is type – safe. This means a generic class can act upon
any data type. Similarly, a generic interface is also type – safe and hence it can use any data type. Generic
classes and generic interfaces are also called ‘parameterized types’ because they use a parameter that
determines which data type they should work upon.
When generic class or generic interface is written, the programmer need not rewrite the same class or interface
whenever he wants to use the class or the interface with a new data type.
Generic types are designed to act upon objects. Hence they cannot work with primitive data types. We use a
generic parameter like <T> or <GT> and write the class as:
class Myclass<T>
{
class code;
}
Here, <T> is called ‘generic parameter’ and it determines at the time of compilation, which data type actually
the programmer wants to use with this class. In the remaining places where a data type is used, the programmer
can use T, as shown below:
class Myclass<T>
{
T obj;
}
Here, the programmer’s intention is to store T type object where T represents any data type. The data type is
specified by the programmer at the time of creating the object to Myclass, as:
Myclass<String> obj=new Myclass<String>();
This means, T assumes String data type and hence java compiler creates the following class internally:
class Myclass
{
String obj;
}
Whenever a generic class or interface is written, java compiler internally creates non – generic version of the
class or interface by substituting the specified data type in place of generic parameter T. this is called ‘erasure’.
32
E.g.:
//a generic class - to store any type of object
//here, T is generic parameter which determines the datatype
class Myclass<T>
{
//declare T type object
T obj;
//a constructor to initialize T type object
Myclass(T obj)
{
this.obj=obj;
}
//a method which returns T type object
T getobj()
{
return obj;
}
}
class Gen
{
public static void main(String args[])
{
33
U stored: 12.123
U stored: vbr
Generic method: We can make a method alone as generic method, by writing the generic parameter before
the method return type as:
<T> void display()
{
Method code;
}
In this case, the method becomes a generic method and can act on any data type. To represent the data type,
we should use T inside the method.
E.g.:
//a generic method - to read and display any type of array elements
class Myclass
{
//this method accepts T type array
static <T>void display(T[] arr)
{
//use for-each loop and read elements of array
for(T i: arr)
System.out.println(i);
}
}
class Gen
{
public static void main(String args[])
{
//read elements from Integer type array using display()
Integer arr1[]={1,2,3,4,5,6};
System.out.println("Reading Integer objects: ");
Myclass.display(arr1);
34
2
3
4
5
6
Reading Double objects:
1.1
2.2
3.3
4.4
5.5
6.6
Reading String objects:
vijay
bhaskar
reddy
vbr
Generic interface: It is possible to develop an interface using generic type concept. An generic interface
looks something like this:
interface Fruit<T>
{
//method that accepts any object
void tellTaste(T fruit);
}
Here, T represents any data type which is used in the interface. Whenever there is an interface, we should also
have implementation classes that implement all the methods of the interface. We can write an implementation
class for the above interface, as:
class AnyFruit<T> implements Fruit<T>
{
public void tellTaste(T fruit)
{
//method body
}
}
Here, T represents generic parameter that shows any data type.
E.g.:
//a generic interface
interface Fruit<T>
{
//method that accepts any object
void tellTaste(T fruit); //public abstract
}
//this class implements Fruit interface
class AnyFruit<T> implements Fruit<T>
{
public void tellTaste(T fruit)
35
{
//know the class name of the object passed to this method
String fruitname=fruit.getClass().getName();
37
Autoboxing/unboxing occurs in expressions:
In general, autoboxing and unboxing take place whenever a conversion into an object or from an object is
required. This applies to expressions. With an expression, a numeric object is automatically unboxed. The
outcome of the expression is reboxed, if necessary.
E.g.:
//autoxoing/unboxing occurs inside expressions
class Autobox3
{
public static void main(String args[])
{
Integer iob,iob1;
int i;
iob=100;
System.out.println("Original value of iob="+iob);
/*the following automatically unboxes iob, performs the
increment, and then reboxes the result back into iob*/
++iob;
System.out.println("After ++iob="+iob);
/*here iob is unboxed, the expression is evaluated,
and the result is reboxedand assigned to iob1*/
iob1=iob+(iob/3);
System.out.println("iob1 after expression="+iob1);
//the same expression is evaluated, but the result is not reboxed
i=iob+(iob/3);
System.out.println("i after expression="+i);
}
}
O/P: G:\>javac autobox3.java
G:\>java Autobox3
Original value of iob=100
After ++iob=101
iob1 after expression=134
i after expression=134
Autoboxing/unboxing Boolean and Character values:
Java also supplies wrappers for boolean and char. These are Boolean and Character. Autoboxing/unboxing
applies to these wrappers, too.
E.g.:
//autoxoing/unboxing a boolean and character
class Autobox4
{
public static void main(String args[])
{
//autobox/unbox a boolean
Boolean b=true;
/*b is auto-unboxed when used in a
conditional expression, such as an if*/
38
if(b)
System.out.println("b is true");
Character ch='x'; //box a char
char ch2=ch; //unbox a char
System.out.println("ch2 is="+ch2);
}
}
O/P: G:\>javac autobox4.java
G:\>java Autobox4
b is true
ch2 is=x
Enumerations:
An enumeration is similar to class that contains only constant values. Enumerations are useful when dealing
with a sequence of fixed values. A constant represents a fixed value and it does not change. For example, as
there are fixed number of days in week, namely Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
and Saturday, you can take these days as constants and construct the following enumeration called days:
enum Days
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
An enumeration is always represented by the word enum, followed by the name of the enumeration, which in
this case is Days. After this you need to write the constants with in a pair of {}. The position of constants
inside an enumeration will be counted from 0 onwards. For example, 0 position is given to Sunday, 1 to
Monday, and 2 to Tuesday.
You can also retrieve all the constants from an enumeration by using the values() method. It is a static method,
which returns all the constants into an array of enumeration type. The syntax to use the values() method is:
Days alldays[]=Days.values();
The values() method is used on Days enumeration with returns all the constants into allDays[] array, so that
allDays[0] represents Sunday, allDays[1] represents Monday and so on. These values can be retrieved
separately again from allDays[] using a for each loop.
for(Days d:allDays)
System.out.println(d);
E.g.:
//create an enumeration with day names
enum Days
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
class displayenum
{
public static void main(String ags[])
{
Days alldays[]=Days.values();
for(Days d:alldays)
System.out.println(d);
39
}
}
40
colortest ct=new colortest(Color.GREEN);
ct.display();
}
}
//a static method to diaply the price upon taking the sequence number
static void getprice(int i)
{
Icecream allicecreams[]=Icecream.values();
System.out.println("pay Rs. "+allicecreams[i].price);
}
}
class getnum
{
public static void main(String args[])throws IOException
{
System.out.println("AVAILABLE ICECREAMS");
for(Icecream ice : Icecream.values())
{
int no=ice.ordinal();
System.out.println(no+" "+ice);
}
41
//get the user choice as a number
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("your choice:");
int choice=Integer.parseInt(br.readLine());
Icecream.getprice(choice);
}
}
O/P: G:\>javac icecream.java
G:\>java getnum
AVAILABLE ICECREAMS
0 vanilla
1 chocolate
2 strawberry
3 pista
your choice:3
pay Rs. 25.0
42