Sie sind auf Seite 1von 34

UNIT V - EXCEPTION HANDLING

Packages and Interfaces, Exception handling, Multithreaded programming, Strings,


Input/Output

PACKAGES
In java, package is the way of grouping a variety of classes and interfaces together.
The package act as a container for classes.
Types of packages in Java
1. Java API Packages
2. User-defined Packages
JAVA API PACKAGES
Java API provides a large number of classes grouped into different packages according
to their functionality.

Java

lang

PACKAGE NAME
java.lang

java.util
java.io
java.awt
java.net
java.applet

util

io

awt

net

applet

CONTENTS
Language support classes that are
automatically imported.
They include classes for primitive types,
strings, math functions etc.,
Contains classes such as hash tables,
vectors, random numbers and date etc.,
They provide facilities for input/output
support
Contains a set of classes for implementing
graphical user interface.
Contains classes for networking
Contains classes for creating and
implementing applets
1

Using system packages


java

Package containing
awt package

awt

Color

Package containing
classes

Font

Graphics

Image

Classes containing
methods

The classes of the package can be included in one or more programs by using the
import statements at the top of the file.
import packagename.classname;
or
import packagename.*;
For example, the Color class in the awt package can be imported in two ways:
1. import java.awt.Color;
or
2. import java.awt.*;

USER DEFINED PACKAGES


1. CREATING A PACKAGE
Syntax
package packagename;
public class classname
{
public returntype methodname()
{
.
}
}

Steps for creating our own package:


1. Decide the name of the package.
2. Create a folder(sub-directory) with the name of the package, where all the
source files are stored.
3. Declare a package using the form:
package packagename;
4. Define a class that is to be put inside the package and declare it as public.
5. Store the file as classname.java inside the folder
6. Switch to the folder,Compile the file. This creates .class file in the folder.
7. Import the package in the other programs.

2. ACCESSING A PACKAGE
The general form of import statement for accessing a user-defined package is as
follows:
import package1.[package2] .classname;
or
import package1.[package2].*;
Here package1 is the name of the top-level package, package2 is inside package1.

PACKAGE EXAMPLE
Create a folder pack1. The package named pack1 contains a single class class1.
Step 1: Creating the package
class1.java
package pack1;
// package declaration
public class class1
// Class defintion
{
public void add(int a, int b)
{
int r1=a+b;
System.out.println("The sum of two numbers:" +r1);
}
public void sub(int a, int b)
{
int r2=a-b;
System.out.println("The difference of two numbers:" +r2);
}
3

public void mul(int a, int b)


{
int r3=a*b;
System.out.println("The product of two numbers:" +r3);
}
public void div(int a, int b)
{
int r4=a/b;
System.out.println("The quotient of two numbers:" +r4);
}
}
Step 2 : Accessing the package in a program
Testpack.java
import pack1.*;

// Accessing the package pack1.

class Testpack

OUTPUT:
The sum of two numbers:30
The difference of two numbers:10
The product of two numbers:100
The quotient of two numbers:15

{
public static void main(String arg[])
{
class1 ob=new class1();

// Object for the class defined inside pack1

ob.add(10,20);

/*Invoking methods inside class1*/

ob.sub(20,10);
ob.mul(10,10);
ob.div(30,2);
}
}

Creating package with multiple classes:


1.
Decide the name of the package.
2.
Create a folder with this name where the source files are stored.
3.
Create classes that are to be placed in the same package in separate
source files and declare the package at the each class.
package packagename;
4.
Switch to the folder and compile each source file. Now, the package
contain .class files for the source files.
==========================================================================
4

INTERFACES:
An interface is a collection of abstract methods and constant variables.
A class implements an interface, thereby inheriting the abstract methods of the

interface.
In java, a subclass cannot have more than one superclass, but it can have more
than one interface.
The concept of interface enables us to create classes without the problems
created by multiple inheritance.

DEFINING AN INTERFACE:
Syntax:

interface interfacename
{
variable declaration;
methods declaration;
}

Syntax for variable declaration:


final datatype variablename=value;
Syntax for method declaration:
returntype methodname(parameter list);
Example:
interface purchase
{
final String prodname=Fan;
final int cost=1500;
void display();
}

EXTENDING INTERFACES:

Like classes, interfaces can also be extended (inherited). This can be done by
using the extends keyword.

Syntax:
1.An interface can be extended from another interface
interface NAME2 extends NAME1

Interface NAME1

{
//declare final variables and abstract methods

Interface NAME2

}
5

2.An interface can be extended from two interfaces

interface NAME3 extends NAME1, NAME2

Interface
NAME1

Interface
NAME2

{
Interface
NAME3

//declare final variables and abstract methods


}

IMPLEMENTING INTERFACES:

An interface can act as a superclass whose properties (final variables and


abstract methods) are inherited by classes.

Syntax:
1.The abstract methods and final variables of an interface can be implemented in a
class by using the following syntax
class NAME2 implements NAME1

Interface NAME1

{
//define the class
Class NAME2

2. In java, a subclass cannot have more than one superclass, but it can have more
than one interface, implemented as follows:
class NAME3 implements NAME1,NAME2

Interface
NAME1

Interface
NAME2

{
//define the class
}

Class
NAME3

3. A subclass can be inherited from a class and interface as follows


class NAME3 extends NAME1 implements NAME2
{
//define the class
}

Class
NAME1

Interface
NAME2

Class
NAME3
6

EXAMPLE: IMPLEMENTING MULTIPLE INHERITANCE USING INTERFACES

In java, a subclass cannot have two superclasses but it can be inherited from
multiple interfaces or a subclass can be inherited from one super class and one
interface.
Class roll

Interface
sports

Class test

Class result

In this hierarchy, the result class has two parents. One is the test class and
the other is an interface named sports. The following program illustrates
the use of interface to substitute multiple inheritance in java.
//PROGRAM : hybrid.java
class roll
{
int rollno;
void getroll(int a)
{
rollno=a;
}
void putroll()
{
System.out.println("Roll no: "+rollno);
}
}
class test extends roll
{
int m1,m2;
void getmark(int x, int y)
{
m1=x;
m2=y;
}
void putmark()
{
System.out.println("Marks obtained");
System.out.println("Mark 1=" +m1);
System.out.println("Mark 2=" +m2);
}
}
7

interface sports
{
final float credit=10.5F;
// Final variable declared
void putcredit();
//Abstract method declared
}
class result extends test implements sports
{
float total;
public void putcredit()
{
total=m1+m2+credit;
putroll();
putmark();
System.out.println("Sports credit:" + credit);
System.out.println("Total score:" +total);
}
}
class hybrid
OUTPUT
{
public static void main(String arg[])
Roll no: 101
{
Marks obtained
result ob=new result();
Mark 1=90
ob.getroll(101);
Mark 2=95
ob.getmark(90,95);
Sports credit:10.5
ob.putcredit();
Total score:195.5
}
}
---------------------------------------------------------------------------------------------------------DIFFERENCE BETWEEN CLASS AND INTERFACE
No
CLASS
INTERFACE
1
The variables of the class can be The variables of an interface are
constant or variable
always declared as constant. i.e their
values are final.
2
The class definition can contain The methods in an interface must be
method definition. The methods abstract. These methods are defined
can be abstract or non-abstract
by the class that implements the
interface
3
Objects can be created
Objects cannot be created. It can only
be inherited
4
It can use access specifiers like It can only use the public access
public, private or protected
specifier

DIFFERENCE BETWEEN INTERFACE AND ABSTRACT CLASS


No
1

INTERFACE
ABSTRACT CLASS
Interface contains abstract methods Abstract class can have methods
and cannot have implementations
with implementation and abstract
methods without implementations
Variables of a interface are final
Variables of an abstract class may
contain non-final variables
Members of an interface are public Members of a abstract class can be
by default
public, private, protected etc.,
A class can implement multiple
A class can extend only one abstract
interfaces
class
Interfaces are slower compared to
Faster than interfaces.
abstract class due to extra
indirection

2
3
4
5

=======================================================================

EXCEPTION HANDLING

Tasks
1.
2.
3.
4.

An exception is a condition caused by a run-time error in the program.


When the java interpreter encounters a runtime error, it creates an exception
object and throws it to the handler.
performed by the error handling code:
Find the problem (Hit the exception)
Inform that an error has occurred (Throw the exception)
Receive the error information(Catch the exception)
Take corrective actions (Handle the exception)

COMMON EXCEPTIONS IN JAVA


Sno
1

EXCEPTION TYPE
ArithmeticException

ArrayIndexOutOfBoundsException

ArrayStoreException

FileNotFoundException

IOException

NumberFormatException

OutOfMemoryException

SecurityException

CAUSE OF EXCEPTION
Caused by math errors such as division by
zero
Caused by bad array indexes
Caused when a program tries to store the
wrong type of data in an array.
Caused by an attempt to open a file that
does not exist.
Caused by general I/O failures, such as
inability to read or write from the file
Caused when a conversion between
strings and number fails
Caused when there is not enough
memory to allocate a new object
Caused when an applet tries to perform
an action that is not allowed by
browsers security setting
9

StackOverFlowException

Caused when the system runs out of


stack space
StringIndexOutOfBoundsException Caused when a program attempts to
access a non-existent character position
in a string

10

CATEGORIES OF EXCEPTIONS IN JAVA


1. CHECKED EXCEPTIONS
These exceptions are explicitly handled in the code with the help of trycatch blocks.
Checked exceptions are extended from the Exception class of the lang
package. (i.e) java.lang.Exception
2. UNCHECKED EXCEPTIONS
These exceptions are not handled in the program code, instead the JVM
handles such exceptions.
Unchecked exceptions are extended from the RunTimeException class
of the lang package. (i.e) java.lang.RunTimeException
BASIC CONCEPT OF EXCEPTION HANDLING

The basic concepts of exception handling are throwing an exception and


catching it.
try block

Throws
exception
object

Statements that causes an


exception

Exception
object creator

catch block
Statements that handles
the exception

Exception
handler

Syntax of try - catch block:


try
{

//Statements that generates exceptions


}
catch(Exception-type e)
{
//Statements that processes the exception
}
10

Try block:
Try block contains code that is likely to cause an error condition and throw an
exception
Catch block:
The catch block catches the exception thrown by the try block and handles it
appropriately.
Example 1: Try-Catch block for exception handling
Error2.java
class Error2
{
public static void main(String arg[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
System.out.println("x=" +x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("y=" + y);
}
}

OUTPUT:
Division by zero
y=1

While executing this program, the program did not stop at the point when
exception is raised.

The Exception is found, handled and then the program continued its execution.

If the same code has been executed without try-catch blocks, then the program
would have terminated after displaying runtime errors.

11

MULTIPLE CATCH BLOCKS


Syntax:
try
{

//statement that generates an exception

}
catch( Exceptiontype1 e)
{
// Statements that processes the exceptiontype1
}
catch( Exceptiontype2 e)
{
// Statements that processes the exceptiontype2
}
EXAMPLE: EXCEPTION HANDLING USING MULTIPLE CATCH BLOCKS
Error3.java
class Error3
{
public static void main(String arg[])
{
int a[ ]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
System.out.println(x= +x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error");
OUTPUT:
}
catch(ArrayIndexOutOfBoundsException e)
Array Index Error
{
System.out.println("Array Index Error");
y=2
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Data Type");
}
int y=a[1]/a[0];
System.out.println(y=+y);
}
}
The array element a[2] does not exist because the array a has only two
elements with indexes a[0] and a[1].

12

Index
a[2]
is
outside
the
array
boundary,
thus
raising
ArrayIndexOutOfBoundsException.
This exception is handled by catch(ArrayIndexOutOfBoundsException e)
Remaining catch blocks are skipped from execution.

THROWS

If a method is capable of causing an exception that it does not handle, then the
throws clause is used in the method definition statement to guard them against
the exception.
A throws keyword lists the types of exceptions that a method might throw.
Example: throwseg.java
class throwseg
{
static void divide() throws ArithmeticException
{
int x=22, y=0,z;
z=x/y;
}
public static void main(String arg[])
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println("Caught the exception:" +e);
}
}
}
OUTPUT:
Caught the exception:java.lang.ArithmeticException: / by zero

FINALLY BLOCK

The finally block may be added immediately after the try block or after the try
block or after the last catch block.
When a finally block is defined, this is guaranteed to execute, whether or not
an exception is thrown.
Syntax:
try
{

//statement that generates an exception

}
13

catch( Exceptiontype1 e)
{
// Statements that processes the exceptiontype1
}
catch( Exceptiontype2 e)
{
// Statements that processes the exceptiontype2
}
finally
{
}

THROWING OWN EXCEPTIONS


Two steps are involved for throwing own exceptions
1. Define a class that extends from the Exception class
2. Define a subclass constructor inside this class to handle the error message by
invoking the super class (Exception class) constructor with super call.
Example:
Write a java program to add two numbers, if the numbers are in the range
0 to 9.If this condition is violated, display an error message on the screen.
import java.util.*;
import java.lang.Exception;
class Newexception extends Exception
//Defining subclass for Exception class
{
Newexception(String message)
{
super(message);
}
}
class testmine
{
public static void main(String arg[])
{
System.out.println("Enter the first number");
Scanner in1=new Scanner(System.in);
int x = in1.nextInt();
//Gets runtime input as integer
System.out.println("Enter the Second number");
Scanner in2=new Scanner(System.in);
int y = in2.nextInt();
//Gets runtime input as integer
int z;
14

try
//Checking whether the given number is 0 - 9
{
if((x<=0) || (x>=9))
{
Newexception e= new Newexception(The number should be in range 0
to 9");
throw e;
//Throws exception object to the handler
}
else if((y<=0) || (y>=9))
{
Newexception e= new Newexception("The number should be in range 0
to 9");
throw e;
//Throws exception object to the handler
}
else
{
z=x+y;
System.out.println("Result=" +z);
}
}
//End of try block
catch(Newexception e)
// Catch block to handle own exception
{
System.out.println(e);
}
finally
{
System.out.println("Execution over");
}

} //End of main()
}
//End of class
OUTPUT:
First run
Enter the first number
5
Enter the Second number
5
Result=10
Execution over
Second run

Enter the first number


5
Enter the Second number
15
Newexception: The number should be in range 0 to 9
Execution over
=======================================================================
15

MULTITHREADING
Thread:
A thread is similar to a program that has a single flow of control. It has a beginning, a
body and an end and executes commands sequentially.

MULTITHREADING

Multithreading is a conceptual programming paradigm where a program is


divided into two or more sub-programs which can be implemented at the same
time in parallel.
Multithreading is a unique property of Java.
A program that contains multiple flow of control is known as multithreaded
program.
Structure of Multithreaded program:

Main Thread

Start

Start

Start

Switching

Thread A

Switching

Thread B

Thread C

The above java program contains four threads. One main thread and three
other threads.
During execution, the main thread and the other threads A,B & C run
concurrently and share the resources.
Since threads in Java are subprograms of the main application program and
share the same memory space, they are known as lightweight threads.
Since all the threads are running on a single processor, the flow of execution is
shared between threads.
The Java interpreter handles the switching of control between the threads
in such a way that it appears like they run concurrently.
Mutlithreading enables the programmer to do multiple things at one time.
For example, we can send printing tasks into background and continue editing
the word document in foreground. This considerably improves the speed of our
operation.
16

CREATING THREADS
Threads can be created in two ways:
1. By extending the Thread class.
2. By implementing the Runnable Interface.
*1.CREATING THREADS BY EXTENDING THE THREAD CLASS.
The process for thread creation involves 3 steps:
Step1: Define a class that extends(inherits) from the Thread class
Syntax:
class mythread extends Thread
{

}
Here, Thread is the predefined class of the lang package, to implement
multithreading process in Java
Step 2: Implement the run() method
The run() is the main portion of any thread. Using this run() method the
threads can be implemented.
The run() method has been inherited from Thread class and overridden to
implement the code to be executed by our thread.
Syntax:
class mythread extends Thread
{
.
..
public void run()
{
//statements implemented for thread
..
..
}
}
Step 3: Start the thread
Create an object for the user-defined thread class defined above.
Start the threads inside the main() function
Syntax:
mythread ob=new mythread();
ob.start();
The start() method is used to invoke the run() method defined inside the class. So,
the thread starts its execution and becomes active after run() method is invoked.
17

*2.CREATING THREADS BY IMPLEMENTING THE RUNNABLE INTERFACE


1. Create a class that implements the Runnable interface
2. Provide the run() method that will be executed by the thread. An object of this
class is a Runnable object.
3. An object of Thread class is created by passing a Runnable object as
argument to the Thread constructor. The Thread object now has a Runnable
object that implements the run() method.
Eg: A ob1=new A();
Thread t1=new Thread(ob1);

//Runnable object
// Thread object

4. The start() method is invoked on the Thread object created in the previously.
t1.start();
---------------------------------------------------------------------------------------------------------EXAMPLE : CREATING THREADS USING THREAD CLASS
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
System.out.println("From Thread A, i=" + i);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5;j++)
{
System.out.println("From Thread B, j=" + j);
}
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5;k++)
{
System.out.println("From Thread C, K=" + k);
}
}
}

OUTPUT:

From
From
From
From
From
From
From
From
From
From
From
From
From
From
From

Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread

A, i=1
C, K=1
C, K=2
C, K=3
C, K=4
C, K=5
B, j=1
B, j=2
B, j=3
B, j=4
B, j=5
A, i=2
A, i=3
A, i=4
A, i=5

18

class Threadtest
{
public static void main(String arg[])
{
A ob1=new A();
B ob2=new B();
C ob3=new C();
ob1.start();
ob2.start();
ob3.start();
}
}
The output for the multithreaded program is not sequential. They do not follow

any specific order.


Once the thread has started, we cannot decide the flow of executing the
statements. There interpreter plays the role of switching between threads.

LIFE CYCLE OF THREAD

The life cycle of a thread includes 5 states


1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

STATE DIAGRAM SHOWING THREAD LIFE CYCLE

19

1. NEWBORN STATE

When we create a thread object, it is said to be in newborn state.


The thread is not scheduled for being executed.
At this state, one of the two things can happen.
i. Schedule it for running using start() method.
ii. Kill it using stop() method.

If the start() method is called the thread moves to the runnable state.

2. RUNNABLE STATE

In the runnable state, the thread is ready for execution and is waiting for
the availability of the processor.

The threads have joined the queue of threads that are waiting for
execution. It will be served in first-come, first-serve manner.

If we want a thread to relinquish(give up) control to another thread, yield()


method is used.

20

3. RUNNING STATE
In this state, the processor has given its time for execution to the threads
waiting in the queue.
A running thread can relinquish( give up) its control in any of the following
situations
Case 1: suspend()
It can be suspended using the suspend() method.
The suspended thread can be re-invoked by using the resume() method.
This approach is useful when we want to block the thread for sometime,
but not want to kill it.

Case 2: sleep(time)
An active thread can be put to sleep for a specified time period, where the
time is in milliseconds.
The thread is out of the runnable queue for this time period.
After the specified time, the thread re-enters the runnable state.

Case 3: wait()
An active can be told to wait until some occurs. This is done by using the wait()
method.
The notify() method schedules to run the thread again.

21

4. BLOCKED STATE
A thread is said to be in blocked state, when it is prevented from entering
into the runnable state and then the running state.
This happens when the thread is subject to suspend, sleep or wait.
A blocked thread is not runnable , not dead.
5. DEAD STATE
A running thread will be destroyed when it has completed the execution of
run() method.
The thread can also be destroyed voluntarily by use of stop() method.
The thread that can be destroyed using the stop() method in either new born
state, active or blocked state.
EXAMPLE USING THREAD METHODS
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
if(i==1)
yield();
System.out.println("From Thread A, i=" + i);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5;j++)
{
System.out.println("From Thread B, j=" + j);
if(j==3)
stop();
}
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5;k++)
{
System.out.println("From Thread C, K=" + k);
if(k==1)
{
try
{

sleep(1000);

}
22

catch(Exception e)
{
System.out.println(e);
}
}
}
}
}

class Threadmethod
{
public static void main(String arg[])
{
A ob1=new A();
B ob2=new B();
C ob3=new C();
ob1.start();
ob2.start();
ob3.start();
}
}

OUTPUT:
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread

B, j=1
B, j=2
B, j=3
C, K=1
A, i=1
A, i=2
A, i=3
A, i=4
A, i=5
C, K=2
C, K=3
C, K=4
C, K=5

This program used the yield() method in thread A. Although thread A started
first, it will give up its control to thread B.

The stop() method in thread B kills the thread.

The sleep() method in thread C, started sleeping when k==1. After 1000
milliseconds, it will wake up and continue its execution. During this sleeping
period thread A will be executed.

Thread priority
The threads of same priority are given equal treatment by the java scheduler.
So, they share the processor in first-come first-serve basis.

Java also permits to set the priority of a thread using setPriority() method.

Syntax:
threadobject. setpriority (integer number);

The Thread class defines several priority constants:


o MIN_PRIORITY = 1
o NORM_PRIORITY=5
o MAX_PRIORITY=10
23

SYNCHRONIZATION

When two or more threads need access to a shared resource (file or memory),
they need some way to ensure that the resource will be used by only one
thread at a time.

The process by which this synchronization is achieved is called thread


synchronization.

For example, Consider that one thread may try to read from the file, while
another thread is still writing to the same file.

Here, conflict occurs. The read process ends with wrong result by reading the
old entries of the file.

To overcome this
synchronization.

problem,

java

enables

technique

known

as

The keyword synchronized is used while declaring both the read() and write()
functions.
Syntax
class A extends Thread
{
public void run()
{
synchronized void read()
{
// Read from the file
}
}
}
class B extends Thread
{
public void run()
{
synchronized void write()
{
// Write contents to the file
}
}
}
When a method is declared as synchronized, Java creates a monitor and hands
it over to the thread that calls the method first.
As long as the thread holds the monitor, no other thread can enter into the
synchronized section.
=======================================================================

24

STRINGS
Strings represent a sequence of characters. In java, strings are the class objects and
implemented using two classes
i)
String
ii)
StringBuffer
A java string is not a character array and is not NULL terminated.
Declaring A String Object:
String stringname=new String(Text);
(or)
String stringname(Text);
---------------------------------------------------------------------------------------------------------JAVA PROGRAM TO PERFORM STRING MANIPULATIONS
---------------------------------------------------------------------------------------------------------stringmanip.java
class stringmanip
{
public static void main(String arg[])
{
String s1="HelloEEE";
String s2;
System.out.println("Original string:" + s1);
// 1. COnverting string to lower case
s2=s1.toLowerCase();
System.out.println("1. Small case string:" + s2);
//2. COnverting to upper case
String s3;
s3=s1.toUpperCase();
System.out.println("2. Upper case string:" + s3);
//3. Replace a character by another
String s4;
s4=s1.replace('H','h');
System.out.println("3. String Replace:" + s4);
25

// 4. Checking if strings are equal


System.out.print("4. Equals method:");
if(s1.equals(s2))
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
// 5. Checking if strings are equal ignoring the case of characters.
System.out.print("5. Equals method by ignoring case of characters:" );
if(s1.equalsIgnoreCase(s2))
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
// 6. Finding string length
int l=s1.length();
System.out.println("6. Length of the string:" + l);
// 7. Accessing characters in a strings
System.out.println("7. The character at position 2 is:" +s1.charAt(1));
// 8. Finding substring
s2=s1.substring(0,4);
System.out.println("8. Substring is of HelloEEE:" +s2);
// 9. Finding index
int pos=s1.indexOf('l');
System.out.println("9. The index of character 'l' is:" +pos);
// 10. Concatenation
System.out.println("10. Concatenated String:" + s1.concat(" Welcome"));
}
}
26

OUTPUT
Original string:HelloEEE
1. Small case string:helloeee
2. Upper case string:HELLOEEE
3. String Replace:helloEEE
4. Equals method:Strings are not equal
5. Equals method by ignoring case of characters:Strings are equal
6. Length of the string:8
7. The character at position 2 is:e
8. Substring is of HelloEEE:Hell
9. The index of character 'l' is:2
10. Concatenated String:HelloEEE Welcome
=====================================================================================

STREAMS AND I/O

Using

A stream in Java is a path along which data flows. It has a source and
destination
In file processing, input refers to the flow of data into a program and output
means the flow of data out of a program.
input and output streams:
Java streams are classified into basic types, input stream and output stream.
Input stream extracts data from the source and sends it to the program
Output stream takes data from the program and sends it to the destination.

27

STREAM CLASSES IN JAVA


The java.io package contains a large number of stream classes that is capable

for processing all the types of data.


The java streams are categorized into two main categories
1. BYTE STREAM CLASSES

Provides support for managing I/O operations on bytes

2. CHARACTER STREAM CLASSES

Provides support for managing I/O operations on characters.

The source or destination may be a memory, a file and a pipe.

CLASSIFICATION OF JAVA STREAM CLASSES


Java Stream Classes

Character Stream
Classes

Byte Stream Classes

Input Stream
Classes

Memory

Output
Stream

File

Pipe

Reader
Classes

Memory

Writer
Classes

File

Pipe

BYTE STREAM CLASSES


The byte stream classes are used for creating and manipulating streams and
files for reading and writing bytes.

Java provides two kinds of byte stream classes


1. InputStream class
2. OutputStream class

28

InputStream class

The input stream classes are used to read 8-bit bytes. It includes the super
class known as InputStream

InputStream methods
Method
read()
read(byte b[])
read(byte b[],int n,int m)
skip(n)
reset()
close()

Description
Reads a byte from the input stream
Reads an array of bytes into b
Reads m bytes starting from nth byte
Skips over n bytes from the input stream
Goes back to the beginning of the stream
Closes the input stream

HIERARCHY OF INPUT STREAM CLASSES

Methods of DataInput Interface


The DataInputStream class extends (inherits) the FilterInputStream class and
implements the interface DataInput.
The methods of DataInput interface are as follows:
1. readShort()
29

2.
3.
4.
5.
6.
7.
8.

readInt()
readLong()
readFloat()
readDouble()
readLine()
readChar()
readBoolean()

OutputStream class

The output stream classes are used to write 8-bit bytes. It includes the super
class known as OutputStream

OutputStream methods
Method
write()
write(byte b[])
write(byte b[], int n, int m)
close()
flush()

Description
Writes a byte to the output stream
Writes all bytes in the array b to the output stream
Writes m bytes of array b starting from nth byte
Closes the output stream
Flushes the output stream

HIERARCHY OF OUTPUT STREAM CLASSES

30

Methods of DataInput Interface

The DataOutputStream class extends (inherits) the FilterOutputStream class


and implements the interface DataOutput.
The methods of DataOutput interface are as follows:
1. writeShort()
2. writeInt()
3. writeLong()
4. writeFloat()
5. writeDouble()
6. writeBytes()
7. writeLine()
8. writeChar()
9. writeBoolean()

CHARACTER STREAM CLASSES

The character streams can be used to read and write 16-bit unicode characters.
Java provides two kinds of byte stream classes
1.Reader Stream class
2.Writer Stream class

Reader Stream classes

The Reader class contains methods that are identical to InputStream class, but
the Reader class is designed to handle character input.

31

Writer Stream classes

The Writer class contains methods that are identical to OutputStream class, but
the Writer class is designed to handle character output.

LIST OF TASKS AND CLASSES IMPLEMENTING INPUT OPERATIONS


Tasks
Perform input operations
Buffering input
Keeping track of line
numbers
Reading from an array
Reading from files
Reading from a pipe
Reading a String
Reading primitive types

CharacterStream classes
Reader
BufferedReader
LineNumberReader

ByteStream classes
InputStream
BufferedInputStream
LineNumberInputStream

CharArrayReader
FileReader
PipedReader
StringReader
None

ByteArrayInputStream
FileInputStream
PipedInputStream
StringInputStream
DataInputStream

LIST OF TASKS AND CLASSES IMPLEMENTING OUTPUT OPERATIONS


Tasks
Perform output operations
Buffering output
Writing to an array

CharacterStream classes
Writer
BufferedWriter
CharArrayWriter

ByteStream classes
OutputStream
BufferedOutputStream
ByteArrayOutputStream
32

Writing to files
Writing to a pipe
Writing to a String
Writing primitive
datatypes

FileWriter
PipedWriter
StringWriter
None

FileOutputStream
PipedOutputStream
StringOutputStream
DataOutputStream

INPUT/OUTPUT EXCEPTIONS
I/O Exception class

Function

EOFException

Signals that an end of the file or end of stream has


been reached unexpectedly during input

FileNotFoundException

Informs that a file could not be found

InterruptedIOException

Warns that an I/O operations has been interrupted

IOException

Signals that an I/O exception of some sort has occurred

READING / WRITING CHARACTERS:


Example for Character Stream classes
Characters.java
import java.io.*;
class Characters
{
public static void main(String arg[])
{
//Declare and create input and output files

File infile=new File (input.txt);


File outfile=new File (output.txt);
FileReader in=null;
FileWriter out=null;
try
{
in=new FileReader(infile);
out=new FileWriter(outfile);

//Opens input file


//Opens ouput file

//Read and write characters till the end

int ch;
while((ch=in.read()) != -1)
{
out.write(ch);
}

//Read until end of the file

//End of try block

33

catch(IOException e)
{
System.out.println(e);
System.out.println(-1);
}
}

READING/WRITING BYTES
Example for Byte Stream classes
WriteBytes.java
import java.io.*;
class WriteBytes
{
public static void main(String arg[])
{
//Declare and initialize a byte array
byte cities [ ]= {'D','E','L','H','I','\n','C','H','E','N','N','A','I'};
int ch;
//Create an output filestream
FileOutputStream out=null;
try
{
out=new FileOutputStream("city.txt"); //connect outputstream to file
out.write(cities);
//write data to the stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
}
//Create an output filestream
FileInputStream in=null;
try
{
in=new FileInputStream("city.txt");
//connect inputstream to file
while((ch=in.read()) != -1)
//Read until end of the file
{
System.out.print( (char) ch);
}
in.close();
}
OUTPUT:
catch(IOException e)
{
System.out.println(e);
}
}

DELHI
CHENNAI

=====================================================================================
34

Das könnte Ihnen auch gefallen