[go: up one dir, main page]

0% found this document useful (0 votes)
31 views33 pages

Unit III Oops

Uploaded by

rambigboss1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views33 pages

Unit III Oops

Uploaded by

rambigboss1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT III

EXCEPTION HANDLING AND I/O


Exceptions - exception hierarchy - throwing and catching exceptions – built-in exceptions,
creating own exceptions, Stack Trace Elements. Input / Output Basics – Streams – Byte
streams and Character streams – Reading and Writing Console – Reading and Writing
Files .
---------------------------------------------------------------------------------------------------------------------

EXCEPTION HANDLING

EXCEPTION:
 An exception is an abnormal condition that arises in a code sequence at run time and
alters the normal program flow.
 In other words, an exception is a run-time error.
 Exception handling works by transferring the execution of a program to an appropriate
exception handler when an exception occurs.

Exception-Handling Fundamentals:
Exception in JAVA
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose to
handle the exception itself, or pass it on. Either way, at some point, the exception is caught and
processed. Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Manually generated exceptions are typically used to report some error
condition to the caller of a method.

Exception-Handling Keywords:
Java exception handling is managed via five keywords:
 try - Set of statement to be monitored for exceptions
 catch - Exception handler , handle the exception
 throw -Used to manually throw an exception
 throws - Throw an exception out of a method
 finally – Will be executed absolutely

Note: try and catch is a indivisible unit. A try without catch is an error but catch can be replaced
by finally. A catch without try is an error.
General form of an exception-handling block:

This is the general form of an exception-handling block:

try
{
// block of code to monitor for errors
// it is the "guarded region.
//"Put code here that might cause some kind of exception.
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
// Put code here that handles this exception.
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
// Put code here that handles this exception.
}
// ...
finally
{
// block of code to be executed after try block ends. //Put code here to release any
resource we allocated in the try clause.
}
// Some other unguarded (normal, non-risky) code begins here

Here, ExceptionType is the type of exception that has occurred.


Try :
The try is used to define a block of code in which exceptions may occur. This block of code is
called a guarded region.

Catch :
Catch is used to define a block of code that handle an exception and it is called Exception
Handler. One or more catch clauses match a specific exception to a block of code that handles
it.

Finally :
A finally block encloses code that is always executed at some point after the try block, whether
an exception was thrown or not. This is the right place to close your files, release your network
sockets, and perform any other cleanup your code requires. If the try block executes with no
exceptions, the finally block is executed immediately after the try block completes. If there was
an exception thrown, the finally block executes immediately after the proper catch block
completes.

throw:
Java throw keyword is used throw an exception explicitly in the code, inside the function or the
block of code.

Throws:
Java throws keyword is used in the method signature to declare an exception which might be
thrown by the function while the execution of the code.

Combination of try, catch, finally :


i. Try with a catch
ii. Try with multiple catches
iii. Try without catch but with finally
iv. Try with catch and with finally
v. Try with multiple catches and with finally

Syntax:

i.try with a catch

try
{
block of code to monitor for errors
}
catch (ExceptionType exOb)
{
Block of code to handle exception of type
ExceptionType
}
ii. Try with multiple catches

try
{
block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
Block of code to handle exception of type ExceptionType1
}
catch (ExceptionType2 exOb)
{
Block of code to handle exception of type ExceptionType2
}

iii. Try without catch but with finally

try
{
block of code to monitor for errors
}
finally
{
Block of code will be executed absolutely whether or not an exception
}

iv.Try with catch and with finally

try
{
block of code to monitor for errors
}
catch (ExceptionType exOb)
{
Block of code to handle exception of type ExceptionType
}
finally
{
Block of code will be executed absolutely whether or not an exception
}
iv.Try with multiple catches and with finally

try
{
block of code to monitor for errors
}
catch (ExceptionType exOb1)
{
Block of code to handle exception of type ExceptionType1
}
catch (ExceptionType exOb2)
{
Block of code to handle exception of type ExceptionType2
}

finally
{
Block of code will be executed absolutely whether or not an exception
}
3.2 EXCEPTION HIERARCHY

All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top
of the exception class hierarchy. Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches. One branch is headed by Exception and the other branch is
topped by Error.

Exception class :
This class is used for exceptional conditions that user programs should catch. This is also the
class that you will subclass to create your own custom exception types. There is an important
subclass of Exception, called RuntimeException. Exceptions of this type are automatically
defined for the programs that you write and include things such as division by zero and invalid
array indexing.

Error class:
The other branch is topped by Error, which defines exceptions that are not expected to be caught
under normal circumstances by your program. Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the run-time environment, itself. Stack overflow
is an example of such an error. Exceptions of type Errors are typically created in response to
catastrophic failures that cannot usually be handled by your program.
STACK TRACE:
The stack trace will always show the sequence of method invocations that led up to the
error. For example, here is another version of the preceding program that introduces the same
error but in a method separate from main( ):

class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}

The resulting stack trace from the default exception handler shows how the entire call stack is
displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
As you can see, the bottom of the stack is main’s line 7, which is the call to subroutine( ), which
caused the exception at line 4. The call stack is quite useful for debugging, because it pinpoints
the precise sequence of steps that led to the error.

3.3 USING TRY AND CATCH


Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. Doing so provides two
benefits. First, it allows you to fix the error. Second, it prevents the program from automatically
terminating.

To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, includes a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (Arithm eticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.

Displaying a Description of an Exception :


Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception. You can display this description in a println( )
statement by simply passing the exception as an argument. For example, the catch block in the
preceding program can be rewritten like this:
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each divide-byzero
error displays the following message:
Exception: java.lang.ArithmeticException: / by zero

Multiple catch Clauses:


A try can have more than one catch clauses , each catching a different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one whose
type matches that of the exception is executed. After one catch statement executes, the others are
bypassed, and execution continues after the try/catch block. The following example traps two
different exception types:
// Demonstrate multiple catch statements.
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no command line
arguments, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].
Output1:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

Output2:
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

Nested try Statements :


The try statement can be nested. That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack. If an
inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match. This continues until one of
the catch statements succeeds, or until the entire nested try statements are exhausted. If no catch
statement matches, then the Java run-time system will handle the exception. Here is an example

// An example of nested try statements.


class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
/* If no command-line args are present, the following statement will
Generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try
{
// nested try block
/* If one command-line arg is used, then a divide-by-zero
Exception will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used, then generate an out-of-
bounds exception. */
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}

catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
that uses nested try statements:
As you can see, this program nests one try block within another.

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

throw
 used to throw an exception explicitly. The general form of throw is shown here:
Syntax:
throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.


Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object,
cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a
parameter in a catch clause, or creating one with the new operator. The flow of execution stops
immediately after the throw statement; any subsequent statements are not executed. The nearest
enclosing try block is inspected to see if it has a catch statement that matches the type of
exception. If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on. If no matching catch is found, then the default
exception handler halts the program and prints the stack trace. Here is a sample program that
creates and throws an exception. The handler that catches the exception rethrows it to the outer
handler.

// Demonstrate throw.
class Demo {
public static void main(String args[])
{
int a=5,b=0,c;
try {
c=a/b;
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("Caught Exception : divide by zero");
}
}

Output:
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this
by including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list


{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.

// This is now correct.


class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}

Output:
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo

finally:
frinally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement matches the exception. This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the beginning of a method with the intent of
disposing of them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
Here is an example program that shows three methods that exit in various ways, none without
executing their finally clauses:
// Demonstrate finally.
class Exc3
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero" + e);
}
//System.out.println("After catch statement.");

finally
{
System.out.println("Finllay block executed");
}
System.out.println("After catch statement.");
}
}

OUTPUT :
Division by zero. java.lang.ArithmeticException: / by zero
Finllay block executed
After catch statement.

3.4 JAVA’S BUILT-IN EXCEPTIONS


Inside the standard package java.lang, Java defines several exception classes , these are called
Built-in Exception.

Java’s Built-in Exceptions Type:


Java’s Built-in exceptions can be classified into two type.

 Unchecked exceptions
 Checked exceptions+
Unchecked Exceptions :
Unchecked exceptions are not checked at compile time. It means if your program is throwing
an unchecked exception and even if you didn’t handle/declare that exception, the program won’t
give a compilation error. All Unchecked exceptions are direct sub classes
of RuntimeException class.

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible
type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
// Demonstrate Unchecked exceptions
.
class Exc3
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero" + e);
}
//System.out.println("After catch statement.");

finally
{
System.out.println("Finllay block executed");
}
System.out.println("After catch statement.");
}
}

OUTPUT :
Division by zero. java.lang.ArithmeticException: / by zero
Finllay block executed
After catch statement.

Checked Exception :
Checked exceptions are checked at compile-time. It means if a method is throwing a checked
exception then it should handle the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will give a compilation error.
Java’s Checked Exceptions Defined in java.lang
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
FileNotFound Exception A requested File does not exist.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.

Example program:
import java.lang.*;
class Student implements Cloneable{
int rollno;
String name;
void getdata(){
rollno=121;
name="RAM";
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
}
class Main
{
public static void main(String args[])
{
try
{
Student s1=new Student();
s1.getdata();
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException e)
{
System.out.println(e);
}
}
}
Checked exceptions Unchecked exceptions
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
A checked exception is checked by the The compiler does not check these type of
compiler exception.
These types of exception can be handled at the These types of exceptions cannot be a catch or
time of compilation handle at the time of compilation, because they
get generated by the mistakes in the program
They are the sub-class of the exception class They are runtime exceptions and hence are not
a part of the Exception class.
Here, the JVM needs the exception to catch Here, the JVM does not require the exception
and handle. to catch and handle

3.5 USER DEFINED EXCEPTION:


Creating Your Own Exception Subclasses:
Although Java’s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications. This is quite
easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).
Your subclasses don’t need to actually implement anything—it is their existence in the type
system that allows you to use them as exceptions.

The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have the
methods defined by Throwable available to them. They are shown in Table.
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a
completed stack trace. This object can be
rethrown.
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception,
null is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace() Returns an array that contains the stack trace, one
element at a time, as an array of
StackTraceElement. The method at the top of the
stack is the last method called before the
exception was thrown. This method is found in
the first element of the array. The
StackTraceElement class gives your program
access to information about each element in the
trace, such as its method name.
Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception
as a cause of the invoking exception. Returns a
reference to the exception
TABLE : The Methods Defined by Throwable
You may also wish to override one or more of these methods in exception classes that you create.
Exception defines four constructors. The two are shown here:
 Exception( )
 Exception(String msg)
The first form creates an exception that has no description.
The second form lets you specify a description of the exception.

Although specifying a description when an exception is created is often useful, sometimes it is


better to override toString( ). Here’s why: The version of toString( ) defined by Throwable (and
inherited by Exception) first displays the name of the exception followed by a colon, which is
then followed by your description. By overriding toString( ), you can prevent the exception name
and colon from being displayed. This makes for a cleaner output, which is desirable in some
cases.
The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overrides the toString( ) method, allowing a carefully
tailored description of the exception to be displayed.
// This program creates a custom exception type.
import java.util.*;
class MyException extends Exception
{
String msg;
MyException()
{
msg = "UserDefined Exception: VoteNotEligibleException";
}

public String toString()


{
//System.out.println("Caught " + msg);
return msg;
}
}
class Main
{
public static void main(String args[])
{ int age;
Scanner s=new Scanner(System.in);
System.out.println("Enter the age");
age=s.nextInt();
try
{
if(age < 18)
throw new MyException();
else
System.out.println("Person is eligible to vote");
System.out.println("Normal exit");
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
Output:

Summary :
 An exception is an abnormal condition that arises in a code sequence at run time and
alters the normal program flow.
 Exception-Handling Keywords:
o try - Set of statement to be monitored for exceptions
o catch - Exception handler , handle the exception
o throw -Used to manually throw an exception
o throws - Throw an exception out of a method
o finally – Will be executed absolutely
 Any exception that is not caught by your program will ultimately be processed by the
default handler.
 The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
 The stack trace will always show the sequence of method invocations that led up to
the error.
 Once an exception is thrown, program control transfers out of the try block into the catch
block and execution never “returns” to the try block from a catch.
INPUT / OUTPUT BASICS:

 Input and output may be text- based IO or binary based.

Text- based IO :
 Handle input and output in terms of 16 bit unsigned character.
 It works with human readable character – such as source code of the program.
 To handle Text- based IO java provides a set of Character stream classes.

Binary based IO
 Handle input and output in terms of byte(8 bit).
 Suitable for reading or writing binary data – such as bit pattern of an image.
 To handle binary- based IO java provides a set of Byte stream classes.

STREAMS:
 Streams are ordered sequence of data that have a source (input stream) or destination
(output stream).
 A stream is an abstraction that either produces or consumes information.
 A stream is linked to a physical device by the Java I/O system.
 An input stream can abstract many different kinds of input: from a disk file, a keyboard,
or a network socket.
 An output stream may refer to the console, a disk file, or a network connection.

BYTE STREAMS AND CHARACTER STREAMS


Java defines two types of streams:
 Byte stream and
 Character stream

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 – such as bit pattern of an image.

Character streams provide a convenient means for handling input and output of characters .It
works with human readable character – such as source code of the program.

The Predefined Streams


Java define three predefined stream variables:
 in,
 out, and
 err.
These fields are declared as public, static, and final within System.
 System.in refers to standard input, which is the keyboard by default. System.in is an
object of type inputStream.
 System.out refers to the standard output stream. By default, this is the console.
 System.err refers to the standard error stream, which also is the console by default.
 System.out and System.err are objects of type PrintStream.
Note : All the stream classes are defined in a package java.io. So before using any of the stream
classes we must import the package java.io., like
import java.io.*;

THE BYTE STREAM CLASSES


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 – such as bit pattern of an image.
Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream. The byte stream classes are shown in Table

InputStream class:
InputStream is an abstract class that defines Java’s model of streaming byte input Most of the
methods in this class will throw an IOException on error conditions. (The exceptions are
mark( ) and markSupported( ).) Table shows the methods in InputStream.
Method of Input stream:

OutpuStream class:
OutputStream is an abstract class that defines streaming byte output. Most of the methods in
this class return void and throw an IOException in the case of errors. (The exceptions are
mark( ) and markSupported( )) Table shows the methods in OutputStream.

Method of Output stream :


CHARACTER STREAMS:
Character streams provide a convenient means for handling input and output of characters. It
works with human readable character – such as source code of the program. at the top of the
character stream hierarchies are the Reader and Writer abstract classes.

THE CHARACTER STREAM CLASSES:

Table

Reader :
Reader is an abstract class that defines Java’s model of streaming character input. All of the
methods in this class (except for markSupported( )) will throw an IOException on error
conditions. Table 19-3 provides a synopsis of the methods in Reader.
Writer :
Writer is an abstract class that defines streaming character output. All of the methods in this
class throw an IOException in the case of errors. Table 19-4 shows a synopsis of the methods in
Writer.
READING AND WRITING CONSOLE:

Reading Console Input :


The preferred method of reading console input is to use a character-oriented stream, which
makes your program easier to internationalize and maintain.

Reading console input is two step process.


1. Create an object for Buffered Reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

2. Invoke read() or readLine();


br.readLine();

BufferedReader :
To obtain a character based stream that is attached to the console, Java has a class called a
BufferedReader. the following line of code creates a BufferedReader that is connected to the
keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

br is a character-based stream that is linked to the console through System.in.


InputStreamReader - which converts bytes to characters.
Reading Characters – read()
To read a character from a BufferedReader, use read( ).

Syntax:
int read( ) throws IOException

it reads a character from the input stream and returns it as an integer value. It returns –1 when the
end of the stream is encountered. it can throw an IOException.

Reading Strings – readLine()


To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

Writing Console Output : print( ) and println( ), write()


The following two classes are used to write to console.
 PrintStream
 PrintWritwer
PrintStream is an output stream derived from OutputStream. System.out is a byte stream
The following three methods of PrintStream are used to write to console.
 print( )
 println( ), and
 write()

write()
void write(int byteval)
This method writes to the stream the byte specified by byteval. Although byteval is declared as
an integer, only the low-order eight bits are written. You will not often use write( ) to perform
console output (although doing so might be useful in some situations), because print( ) and
println( ) are substantially easier to use.

Example 1:
import java.io.*;
class IOExample
{
public static void main(String args[]) throws IOException
{

int a,b,c;
// Step 1. Create an object for BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Step 2. use read() or readLine() to read the inputs
System.out.println("Enter the value of A:");
a = Integer.parseInt(br.readLine());
System.out.println("Enter the value of B:");
b = Integer.parseInt(br.readLine());
c= a+ b;
System.out.println("sum ="+ c);
}
}

Output :
Enter the value of A:
5
Enter the value of B:
6
sum =11

Example 2:
Write a java program using stream to find sum of 3 numbers, find largest and smallest of 3
numbers and test whether third number is product of first and second numbers.

import java.io.*;
class IODemo
{
int a,b,c,sum,product;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

void input()
{
try
{

System.out.println("Enter the value of A:");


a = Integer.parseInt(br.readLine());
System.out.println("Enter the value of B:");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the value of C:");
c = Integer.parseInt(br.readLine());
}
catch(IOException ex)
{
System.out.println("Exception Caught"+ex);
}
}
void findsum()
{
sum = a+b+c;
System.out.println("Sum of A,B,C = "+sum);
}

void findLarger()
{
if (a>b && a>c)
{
System.out.println("A is Greatest");
}
else if(b>c)
{
System.out.println("B is Greatest");
}
else
{
System.out.println("C is Greatest");
}
}

void findSmaller()
{
if (a<b && a<c)
{
System.out.println("A is Smallest");
}
else if(b<c)
{
System.out.println("B is Smallest");
}
else
{
System.out.println("C is Smallest");
}

void findProduct()
{
product = a*b;
if(c==product)
{
System.out.println("C is the product of A and B");
}
else
{
System.out.println("C is NOT the product of A and B");
}

public static void main(String args[])


{
IODemo ob =new IODemo();
ob.input();
ob.findsum();
ob.findLarger();
ob.findSmaller();
ob.findProduct();
}
}

Output :
Enter the value of A:
2
Enter the value of B:
4
Enter the value of C:
5
Sum of A,B,C = 11
C is Greatest
A is Smallest
C is NOT the product of A and B.

READING AND WRITING FILES:

Reading and writing files in java can be done using following classes.
 FileInputStream(String fileName) throws FileNotFoundException
 FileOutputStream(String fileName) throws FileNotFoundException
 FileReader(String fileName) throws FileNotFoundException
 FileWriter(String fileName) throws FileNotFoundException

Reading files:

Reading input file is two step process.


1. Create an object for FileStream or FileReader class
FileInputStream fin = new FileInputStream("k:/myfile.txt");
2. Invoke read() or readLine();
fin.read

Example program:
/*This program, read the content file and display it to console. */
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
/*Create an object for FileInputStream, it throws FileNotFoundException if file is unavailable */

FileInputStream fin = new FileInputStream("k:/file1.txt");

int c;

/* Method read() of FileInputStream class also throws exception: IOException */


while(( c = fin.read() ) != -1)
{
System.out.print((char)c);
}

/*The method close() closes the file input stream It throws IOException*/
fin.close();
}
catch(IOException e)
{
System.out.println("File not found " + e);
}
}
}

Input File : file1.txt


Chennai
Delhi
Mumbai
Kolkata

Output:
Chennai
Delhi
Mumbai
Kolkata
Input File : file1.txt
Output:
File not found java.io.FileNotFoundException: k:\file1.txt (The system cannot find the file
specified)

As file1.txt is not available tint specified location it throw an exception


java.io.FileNotFoundException

Example program 2: - File copy

/*This program, read the content file and display it to console. */


import java.io.*;
class FileCopyDemo
{
public static void main(String args[])
{
try
{
/*Create an object for FileInputStream, it throws FileNotFoundException if file is
unavailable */
FileInputStream fin = new FileInputStream("k:/file1.txt");

/*Create an object for FileOutStream */


FileOutputStream fout = new FileOutputStream("k:/file2.txt");
int c;

/*Read data from file1.txt*/


while(( c = fin.read() ) != -1)
{
//Write the data to file2.txt
fout.write((char)c);
}
System.out.println("File was succesfully copied");

/*The method close() closes the file input stream and file output stream It throws IOException*/
fin.close();
fout.close();
}
catch(IOException e)
{
System.out.println("File not found " + e);
}
}
}
Input File : file1.txt
Chennai
Delhi
Mumbai
Kolkata

Output:
File was successfully copied.

Explanation:
The above program creates a new file named file2.txt.
Output File : file2.txt
Chennai
Delhi
Mumbai
Kolkata

You might also like