You are on page 1of 42

GEETHANJALI INSTITUTE OF SCIENCE & TECHNOLOGY: NELLORE

Lecture Notes

Course / Branch: B. Tech. / ECE Academic Year: 2022-23


Name of the Subject: Java Programming (20A05505a) Year / Semester: III / I
Name of the Staff: Mr. P. Vijay Bhaskar Reddy Department: CSE

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.

Dealing with errors:


There are basically 3 types of errors in the java program:
1. Compile – time errors: These are syntactical errors found in the code, due to which a program fails
to compile. For example, forgetting a semicolon at the end of a java statement, or writing a statement
without proper syntax will result in compile – time error.
E.g.:
//compile - time error
class error
{
public static void main(String a[])
{
System.out.println("Hai NECG")
System.out.println("Hello MCA")
}
}

O/P: F:\JAVA>javac compile.java


compile.java:6: error: ';' expected
System.out.println("Hai NECG")
^
compile.java:7: error: ';' expected
System.out.println("Hello MCA")
^
2 errors
In this program, we are not writing a semicolon at the end of the statements. This is will be detected
by the java compiler.
2. Run – time errors: These errors represent inefficiency of the computer system to execute a particular
statement. For example, inefficient memory to store something or inability of the microprocessor to
execute some statement come under run – time errors.
E.g.:
//run - time error
1
class Error
{
public static void main()
{
System.out.println("Hello");
System.out.println("where is error");
}
}

O/P: F:\JAVA>javac run.java

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);
}
}

O/P: F:\JAVA>javac logical.java

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.

Benefits of exception handling:


1. Exception handling provides a powerful mechanism for controlling complex programs that have many
dynamic run – time characteristics.
2. By handling exceptions, a programmer can make his programs ‘robust’. It means the java program will
not abnormally terminate if all the possible exceptions have been handled properly.
3. To provide user understandable messages when exception is raised, so that user can take decision
without developer’s help.

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");
}
}

O/P: F:\JAVA>javac exception.java


F:\JAVA>java Ex 1 2 3
open the files
n= 3
a= 15
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");
}
}
}

O/P: F:\JAVA>javac exception1.java

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();
}
}

O/P: F:\JAVA>javac throw.java

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.

//Not handling the exception


import java.io.*;
class Sample
{
private String name;
void accept()throws IOException
{
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[])throws IOException
{
Sample s=new Sample();
s.accept();
s.display();
}
}

O/P: F:\JAVA>javac throws1.java

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");
}
}
}

O/P: F:\JAVA>javac exception1.java

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");
}
}
}

O/P: F:\JAVA>javac rethrow.java


F:\JAVA>java B
Please see the index is within the range
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:

Exception class Meaning


ArithmeticException Thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index.
The index is either negative 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 Raised when a file is not accessible or does not open
IOException Thrown when an input – output operation failed or interrupted.
InterruptedException Thrown when a thread is waiting, sleeping, or doing some processing,
and it is interrupted.
NoSuchFieldException Thrown when a class does not contain the field or variable specified.
NoSuchMethodException Thrown when accessing a method which is not found.
NullPointerException Raised when referring to the members of null object.
NumberFormatException Raised when a method could not convert a string into a number format.
RuntimeException This represents any exception which occurs doing runtime.
StringIndexOutOfBoundsException Thrown by String class methods to indicate that an index is either
negative or greater than the size of the string.

2. User – defined exceptions / creating own exception sub classes:


Sometimes, the built – in exceptions in java are not able to describe a certain situation. In such cases,
like the built – in exceptions, the programmer can also create his own exceptions which are called user
– defined exceptions. Sometimes input is given to the application may not violate runtime rules but it
violates my application business rules. Such violation of business rule JVM will not treat as an
abnormal event and hence it will not throw any exception. As a developer we want to stop the task
processing as the business rule is violated. The best way to do so is throw the user defined exception
explicitly. In order to create user defined exception class, the role is that the class must extends

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();
}
}
}

O/P: F:\JAVA>javac ownexception.java

F:\JAVA>java MyException
ACCNO CUSTOMER BALANCE
1001 vijay 100.0
MyException: Balance amount is less at MyException.main(ownexception.java:31)

Handling multiple exceptions;


Most of the times there is a possibility of more than one exception present in the program. In this case, the
programmer should write multiple catch blocks to handle to each one of them. A single try block can be
followed by several catch blocks.
E.g.:
//Demonstrate multiple catch statements
class MultipleCatch
{
public static void main(String args[])
{
try
{
int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("a= "+a);
int b[]={10,20,30};
b[20]=100;
}

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");
}

}
}

O/P: F:\JAVA>javac exception2.java

F:\JAVA>java MultipleCatch
n= 0
java.lang.ArithmeticException: / by zero
please pass data while running this program

F:\JAVA>java MultipleCatch 315 316


n= 2
a= 22
java.lang.ArrayIndexOutOfBoundsException: 20
please see that the array index is within the range

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.

Character stream classes:


17
Character or text streams can always store and retrieve data in the form of characters (or text) only. It means
text streams are more suitable for handling text files like the ones we create in notepad. They are not suitable
to handle the images, audio, or video files. Character streams are defined by using two class hierarchies. At
the top are two abstract classes, Reader and Writer. Java has several concrete sub classes of each of these.
The abstract classes Reader and Writer define several key methods that the other stream classes implement.
Two of the most important methods are read() and write(), which read and write characters of data
respectively. These methods are overridden by derived stream classes. The important classes of character
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);

//attach myfile to FileOutputStream


FileOutputStream fout=new FileOutputStream("myfile1.txt",true);

System.out.println("Enter text (@ at the end): ");


char ch;

//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);

//close the file


fout.close();
}
}

O/P: F:\JAVA>javac filecre.java


F:\JAVA>java FileCreate
Enter text (@ at the end):
this is vijay
@
F:\JAVA>type myfile1.txt
this is vijay
this is vijay

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.

Improving efficiency using BufferedOutputStream;


If buffered classes are used, they provide a buffer (temporary block of memory), which is first filled with
characters and then all the characters from the buffer can be at once written into the file. Buffered classes
should be used always in connection to other stream classes. For example, BufferedOutputStream can be used
along with FileOutputStream to write data into a file.
Thus, by using buffered classes, the speed of writing is improved. In the same way, we can use buffered classes
for improving the speed of reading operation also.
We can attach FileOutputStream to BufferedOutputStream as:
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
Here, the buffer size is declared as 1024 bytes. If the buffer size is not specified, then a default buffer size of
512 bytes is used.
E.g.:
//creating a text file using BufferedOutputStream
import java.io.*;
class FileCreate
{
public static void main(String args[])throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);

//attach myfile to FileOutputStream in append mode


FileOutputStream fout=new FileOutputStream("myfile.txt", true);

20
//attach FileOutputStream to BufferedOutputStream
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);

System.out.println("Enter text (@ at the end): ");


char ch;

//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);

//close the file


bout.close();
}
}

O/P: F:\JAVA>javac filecre1.java

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

Reading data from a file using FileInputStream:


FileInputStream: It must be used to read data from a file.
Constructors:
1. FileInputStream(String name) throws FileNotFoundException
2. FileInputStream(File f) throws FileNotFoundException
3. FileInputStream(FileDescriptor fd) throws FileNotFoundException
FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible to read data
from a text file using FileInputStream.
 First, we should attach the file to a FileInputStream as shown below:
FileInputStream fin=new FileInputStream(“myfile.txt”);

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");

System.out.println("File contents: ");

/*read characters from FileInputStream and write them


to moniter. Repeat this till the end of file*/
int ch;
while((ch=fin.read())!= -1)
System.out.print((char)ch);
//close the file
fin.close();
}
}
O/P: F:\JAVA>javac fileread.java

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();

//attach the file to FileInputStream


FileInputStream fin=null; //assign nothing to fin

//check if file exists or not


try
{
fin=new FileInputStream(fname);
}
catch(FileNotFoundException fe)
{
System.out.println("File not found");
return;
}
//attach FileInputStream to BufferedInputStream
BufferedInputStream bin=new BufferedInputStream(fin);
System.out.println("File contents: ");
/*read characters from BufferedInputStream and write them
to moniter. Repeat this till the end of file*/
int ch;
while((ch=bin.read())!= -1)
System.out.print((char)ch);
//close the file
bin.close();
}
}
O/P: F:\JAVA>javac fileread1.java
F:\JAVA>java FileRead

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

File management using File class:


File class of java.io package provides some methods to know the properties of a file or directory. First of all,
we should create the File class object by passing the file name or directory name to it.
File obj=new File(file name);
File obj=new File(directory name);
File obj=new File(“path”,file name);
File obj=new File(“path”,directory name);
File class methods:
File class includes the following methods:
 boolean isFile(): This method returns true if the File object contains a file name, otherwise false.
 boolean isDirectory: This method returns true if the File object contains a directory name.
 boolean canRead():This method returns true if the File object contains a file which is readable.
 boolean canWrite():This method returns true if the file is writable.
 boolean canExecute():This method returns true if the file is executable.
 boolean exists():This method returns true when the File object contains a file or directory which
physically exists in the computer.
 String getParent(): This method returns the name of the parent directory of a file or directory.
 String getPath(): This method returns the name of the directory path of a file or directory.
 String getAbsolutePath(): This method returns the absolute directory path of a file or directory
location.
 long length(): This method returns a number that represents the size of the file in bytes.
 boolean delete(): This method deletes the file or directory whose name is in File object.
 boolean createNewFile(): This method automatically creates a new, empty file indicated by a File
object, if and only if a file with this name does not yet exist.
 boolean mkdir(): This method creates a directory whose name is given in File object.
 boolean renameTo(File newname): This method changes the name of the file as new name.
 String []list(): This method returns an array of strings naming the files and directories in the
directory.

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;

//for reading data from args[0]


FileInputStream fin=new FileInputStream(args[0]);

//for writing data into args[1]


FileOutputStream fout=new FileOutputStream(args[1]);

//read from FileInputStream and write into FileOutputStream

29
while((ch=fin.read())!=-1)
fout.write(ch);

//close the files


fin.close();
fout.close();
System.out.println("1 file copied");
}
}

O/P: F:\JAVA>javac filecpy.java

F:\JAVA>java CopyFile filecpy.java filecpy1.java


1 file copied

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;

//for reading data from args[0]


FileInputStream fin=new FileInputStream(args[0]);

//for writing data into args[1]


FileOutputStream fout=new FileOutputStream(args[1]);

//read from FileInputStream and write into FileOutputStream


while((ch=fin.read())!=-1)
fout.write(ch);

//close the files


fin.close();
fout.close();
System.out.println("1 file copied");
}
}

Random access file operations:


Sequential files can read / write only at the beginning / ending of the file. On the other hand, random access
files allow us to read from or write to any location in the file. The class RandomAccessFile offers methods
that allow specified mode accesses such as ‘read only’ and ‘read - write’ to files. Since RandomAccessFile is
not inherited from InputStream or OutputStream. It implements both DataInput and DataOutput which deal

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);

file.seek(0); //go to the begining

//reading from the file


System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());

file.seek(2); //go to the second item


System.out.println(file.readInt());

//go to the end and append true to the file


file.seek(file.length());
file.writeBoolean(true);
file.close();
}
}

O/P: E:\vbr\JAVA>javac random.java


E:\vbr\JAVA>java Random
V
2012
3.14
2012

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[])
{

//create Integer class object


Integer i=12; //this is same as: Integer i=new Integer(12);

//create Myclass object and store Integer object in it


Myclass<Integer> obj=new Myclass<Integer>(i);

//retrieve Integer object by calling getobj()


System.out.println("U stored: "+ obj.getobj());

//in the same way, use Myclass for storing


//Float object and retieve it
Float f=12.123f; //same as Float f=new Float(12.123f);
Myclass<Float> obj1=new Myclass<Float>(f);
System.out.println("U stored: "+ obj1.getobj());

//we can use Myclass to store String type data also


Myclass<String> obj2=new Myclass<String>("vbr");
System.out.println("U stored: "+ obj2.getobj());
}
}
O/P: G:\>javac generic.java
G:\>java Gen
U stored: 12

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);

//read elements from Double type array using display()


Double arr2[]={1.1,2.2,3.3,4.4,5.5,6.6};
System.out.println("Reading Double objects: ");
Myclass.display(arr2);

//read elements from String type array using display()


String arr3[]={"vijay", "bhaskar", "reddy", "vbr"};
System.out.println("Reading String objects: ");
Myclass.display(arr3);
}
}
O/P: G:\>javac generic1.java
G:\>java Gen
Reading Integer objects:
1

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();

//then decide the taste and display


if(fruitname.equals("Banana"))
System.out.println("Banana is sweet");
else if(fruitname.equals("Orange"))
System.out.println("Orange is sour");
}
}
class Banana
{
}
class Orange
{
}
class Gen
{
public static void main(String args[])
{
//create Banana object and pass it to AnyFruit class
Banana b=new Banana();
AnyFruit<Banana> fruit1=new AnyFruit<Banana>();
fruit1.tellTaste(b);

//create Orange object and pass it to AnyFruit class


Orange o=new Orange();
AnyFruit<Orange> fruit2=new AnyFruit<Orange>();
fruit2.tellTaste(o);
}
}
O/P: G:\>javac generic2.java
G:\>java Gen
Banana is sweet
Orange is sour

Autoboxing and auto – unboxing:


Beginning with JDK5, java added 2 important features: autoboxing and auto – unboxing.
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object.
Auto – unboxing is the process by which the value of boxed object is automatically extracted (unboxed) from
a type wrapper when its value is needed. There is no need to call a method such as intValue() or
doubleValue().
E.g.:
Integer iob=100; //autobox an int
36
Notice that no object is explicitly created through the use of new. Java handles this automatically.
To unbox an object, simply assign that object reference to a primitive type variable. For e.g. to unbox iob, you
can use
int i=iob; //auto – unbox
E.g.:
//demonstrate autoboxing/unboxing
class Autobox
{
public static void main(String args[])
{
Integer iob=100; //autobox an int
int i=iob; //auto-unbox
System.out.println(i + " " + iob);
}
}
O/P: G:\>javac autobox.java
G:\>java Autobox
100 100
Autoboxing and methods:
In addition to simple case of assignments, autoboxing automatically occurs whenever a primitive type must
be converted into an object; auto – unboxing takes place whenever an object must be converted into a primitive
type. Thus, autoboxing/auto – unboxing might occur when an argument is passed to a method, or when a value
is returned by a method.
E.g.:
/*autoxoing/unboxing takes place with
method parameters and return values*/
class Autobox2
{
//take an Integer parameter and return an int value
static int m(Integer v)
{
return v; //auto-unbox to int
}
public static void main(String args[])
{
Integer iob=m(100);
System.out.println(iob);
}
}
O/P: G:\>javac autobox2.java
G:\>java Autobox2
100
In the program, notice that display() specifies an Integer parameter and returns an int result. Inside main(),
display() is passed the value 100. Because display() is expecting an Integer, this value is automatically boxed.
Then, display() returns the int equivalent of its argument. This causes v to be auto – unboxed. Next, this int
value is assigned to iob in main(), which causes the int return value to be autoboxed.

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
}
}

O/P: G:\>javac enum.java


G:\>java displayenum
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Since enumeration has constants, they can be used to perform various tasks inside a switch statement
depending upon the choice of the user.
E.g.:
//create a color enumeration with color names as constants
enum Color
{
RED, GREEN, BLUE, WHITE, BLACK
}
class colortest
{
//enumeration constant is declared as instance variable
Color c;
//initialize the variable
colortest(Color c)
{
this.c=c;
}
void display()
{
switch(c)
{
case RED: System.out.println("Red color");
break;
case GREEN: System.out.println("Green color");
break;
case BLUE: System.out.println("Blue color");
break;
case WHITE: System.out.println("White color");
break;
default: System.out.println("Not a good color");
}
}
public static void main(String args[])
{

40
colortest ct=new colortest(Color.GREEN);
ct.display();
}
}

O/P: G:\>javac color.java


G:\>java colortest
Green color
All enumerations in java are considered as class types. In fact, they are all sub classes of the Enum call of the
java.lang package. Since all enumerations inherit the Enum class, they cannot inherit any other class. Since
enumerations are class types, it is possible to write instance variables, constructors and methods inside the
enumeration. There is a method ordinal() that is available in the Enum class. This method retrieves the position
of the constants in the enumeration. The ordinal() method starts counting from 0 onwards.
E.g.:
import java.io.*;
enum Icecream
{
//constants with values
vanilla(20.00), chocolate(22.50), strawberry(23.00), pista(25.00);

//an instance variable


private double price;

//a parameterized constructor which initializes price with p


Icecream(double p)
{
price=p;
}

//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

You might also like