0% found this document useful (0 votes)
12 views30 pages

Unit V Notes Java

The document provides an overview of event handling in Java, focusing on the java.awt.event package and the Delegation Event Model, which includes sources, listeners, and events. It details various event types such as ActionEvent, ItemEvent, KeyEvent, and MouseEvent, along with their constructors and methods. Additionally, it discusses the implementation of event listener interfaces like ActionListener, ItemListener, and MouseListener, which are essential for processing events in Java applications.

Uploaded by

318Giri Prasad C
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)
12 views30 pages

Unit V Notes Java

The document provides an overview of event handling in Java, focusing on the java.awt.event package and the Delegation Event Model, which includes sources, listeners, and events. It details various event types such as ActionEvent, ItemEvent, KeyEvent, and MouseEvent, along with their constructors and methods. Additionally, it discusses the implementation of event listener interfaces like ActionListener, ItemListener, and MouseListener, which are essential for processing events in Java applications.

Uploaded by

318Giri Prasad C
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/ 30

Unit-V

Introduction to Event Handling

Events are supported by the java.awt.event package.

Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.

The Delegation Event Model has the following key participants

Source - The source is an object on which event occurs.


Listener - is responsible for generating response to an event.

Events - an event is an object that describes a state change in a source.

Event Sources
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event.

A source must register listeners in order for the listeners to receive notifications about a specific
type of event. Each type of event has its own registration method. Here is the general form

public void addTypeListener(TypeListener el)

Example:

 The method that registers a keyboard event listener is called addKeyListener().


 The method that registers a mouse motion listener is called addMouseMotionListener( ).

Event Listeners

A listener is an object that is notified when an event occurs.

It has two major requirements.

First, it must have been registered with one or more sources to receive notifications about
specific types of events.

Second, it must implement methods to receive and process these notifications

Understanding ActionEvent & ItemEvent

ActionEvent

1|Page
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected. The ActionEvent class defines four integer constants that can be used to
identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK,
META_MASK, and SHIFT_MASK. In addition, there is an integer constant,
ACTION_PERFORMED, which can be used to identify action events. ActionEvent has these
two constructors:

ActionEvent(Object src, int type, String cmd)


ActionEvent(Object src, int type, String cmd, int modifiers)

Here, src is a reference to the object that generated this event. The type of the event is specified
by type, and its command string is cmd. The argument modifiers indicates which modifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated.

ItemEvent

An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu
item is selected or deselected. There are two types of item events, which are identified by the
following integer constants:

DESELECTED : The user deselected an item.


SELECTED : The user selected an item.

In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that


signifies a change of state.

ItemEvent has this constructor:

ItemEvent(ItemSelectable src, int type, Object entry, int state)

Here, src is a reference to the component that generated this event. For example, this
might be a list or choice element. The type of the event is specified by type. The specific

2|Page
item that generated the item event is passed in entry. The current state of that item is in
state.
The getItem( ) method can be used to obtain a reference to the item that generated an
event. Its signature is shown here:

Object getItem( )

The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectable object
that generated an event. Its general form is shown here:

ItemSelectable getItemSelectable( )

Lists and choices are examples of user interface elements that implement the ItemSelectable
interface.

The getStateChange( ) method returns the state change (i.e., SELECTED or DESELECTED)
for the event. It is shown here:

int getStateChange( )

Understanding KeyEvent & MouseEvent

events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED,


and KEY_TYPED. The first two events are generated when any key is pressed or released. The
last event occurs only when a character is generated. Remember, not all key presses result in
characters. For example, pressing the SHIFT key does not generate a character.

There are many other integer constants that are defined by KeyEvent. For example, VK_0
through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and
letters. Here are some others:

VK_ENTER
V K_ESCAPE
V K_CANCEL

3|Page
VK_UP
VK_DOWN
V K_LEFT
V K_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
V K_SHIFT
VK_ALT
VK_CONTROL

The VK constants specify virtual key codes and are independent of any modifiers, such as
control, shift, or alt.

KeyEvent is a subclass of InputEvent and has these two constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the key was pressed is passed in when. The
modifiers argument indicates which modifiers were pressed when this key event occurred. The
virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character
equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.

The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns
the key code. Their general forms are shown here:

char getKeyChar( )
int getKeyCode( )

4|Page
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When
a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

The MouseEvent Class

There are seven types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
MOUSE_CLICKED

The user clicked the mouse.

MOUSE_DRAGGED : The user dragged the mouse.


MOUSE_ENTERED : The mouse entered a component.
MOUSE_EXITED : The mouse exited from a component.
MOUSE_MOVED : The mouse moved.
MOUSE_PRESSED : The mouse was pressed.
MOUSE_RELEASED : T he mouse was released.

MouseEvent is a subclass of InputEvent and has this constructor:

MouseEvent(Component src, int type, long when, int modifiers,

int x, int y, int clicks, boolean triggersPopup)

Here, src is a reference to the component that generated the event. The type of the event
is specified by type. The system time at which the mouse event occurred is passed in
when. The modifiers argument indicates which modifiers were pressed when a mouse
event occurred. The coordinates of the mouse are passed in x and y. The click count is
passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to
appear on this platform.

The most commonly used methods in this class are getX( ) and getY( ). These return the

5|Page
X and Y coordinates of the mouse when the event occurred. Their forms are shown here:

int getX( )
int getY( )

Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse.
It is shown here:

Point getPoint( )

It returns a Point object that contains the X, Y coordinates in its integer members: x and y.

The translatePoint( ) method changes the location of the event. Its form is shown here:

void translatePoint(int x, int y)

Here, the arguments x and y are added to the coordinates of the event.

The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here:

int getClickCount( )

The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on
this platform. Its form is shown here:

boolean isPopupTrigger( )

TextEvent, WindowEvent, ComponentEvent

TextEvent

6|Page
The TextEvent is generated when character is entered in the text fields or text area. The
TextEvent instance does not include the characters currently in the text component that generated
the event rather we are provided with other methods to retrieve that information.
Class declaration
Following is the declaration for java.awt.event.TextEvent class:
public class TextEvent
extends AWTEvent
Field
Following are the fields for java.awt.event.TextEvent class:
 static int TEXT_FIRST --The first number in the range of ids used for text events.
 static int TEXT_LAST --The last number in the range of ids used for text events.
 static int TEXT_VALUE_CHANGED --This event id indicates that object's text
changed.

Class constructors

TextEvent(Object source, int id)

WindowEvent

The object of this class represents the change in state of a window.This low-level event is
generated by a Window object when it is opened, closed, activated, deactivated, iconified, or
deiconified, or when focus is transfered into or out of the Window.
Class declaration
Following is the declaration for java.awt.event.WindowEvent class:
public class WindowEvent
extends ComponentEvent
Field
Following are the fields for java.awt.event.WindowEvent class:
 static int WINDOW_ACTIVATED --The window-activated event type.
 static int WINDOW_CLOSED -- The window closed event.
 static int WINDOW_CLOSING -- The "window is closing" event.
 static int WINDOW_DEACTIVATED -- The window-deactivated event type.
 static int WINDOW_DEICONIFIED -- The window deiconified event type.

7|Page
 static int WINDOW_FIRST -- The first number in the range of ids used for window
events.
 static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type.
 static int WINDOW_ICONIFIED -- The window iconified event.
 static int WINDOW_LAST -- The last number in the range of ids used for window
events.
 static int WINDOW_LOST_FOCUS -- The window-lost-focus event type.
 static int WINDOW_OPENED -- The window opened event.
 static int WINDOW_STATE_CHANGED -- The window-state-changed event type.
Class constructors

S.N. Constructor & Description

1 WindowEvent(Window source, int id)


Constructs a WindowEvent object.

2 WindowEvent(Window source, int id, int oldState, int newState)


Constructs a WindowEvent object with the specified previous and new window
states.

3 WindowEvent(Window source, int id, Window opposite)


Constructs a WindowEvent object with the specified opposite Window.

4 WindowEvent(Window source, int id, Window opposite, int oldState, int newState)
Constructs a WindowEvent object.

ComponentEvent

The Class ComponentEvent represents that a component moved, changed size, or changed
visibility
Class declaration
Following is the declaration for java.awt.event.ComponentEvent class:
public class ComponentEvent
extends AWTEvent

8|Page
Field
Following are the fields for java.awt.Component class:
 static int COMPONENT_FIRST -- The first number in the range of ids used for
component events.
 static int COMPONENT_HIDDEN --This event indicates that the component was
rendered invisible.
 static int COMPONENT_LAST -- The last number in the range of ids used for
component events.
 static int COMPONENT_MOVED -- This event indicates that the component's position
changed.
 static int COMPONENT_RESIZED -- This event indicates that the component's size
changed.
 static int COMPONENT_SHOWN -- This event indicates that the component was made
visible.

Class constructors

ComponentEvent(Component source, int id)

Introduction to Event Listener Interfaces

The Event listener represent the interfaces responsible to handle events. Java provides us various
Event listener classes but we will discuss those which are more frequently used. Every method of
an event listener method has a single argument as an object which is subclass of EventObject
class. For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.
EventListner interface
It is a marker interface which every listener interface has to extend.This class is defined in
java.util package.
Class declaration
Following is the declaration for java.util.EventListener interface:
public interface EventListener
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.

9|Page
Sr. No. Control & Description

1 ActionListener
This interface is used for receiving the action events.

2 ComponentListener
This interface is used for receiving the component events.

3 ItemListener
This interface is used for receiving the item events.

4 KeyListener
This interface is used for receiving the key events.

5 MouseListener
This interface is used for receiving the mouse events.

6 TextListener
This interface is used for receiving the text events.

7 WindowListener
This interface is used for receiving the window events.

8 AdjustmentListener
This interface is used for receiving the adjusmtent events.

9 ContainerListener
This interface is used for receiving the container events.

10 MouseMotionListener
This interface is used for receiving the mouse motion events.

11 FocusListener
This interface is used for receiving the focus events

Working with ActionListener

The class which processes the ActionEvent should implement this interface.The object of that
class must be registered with a component. The object can be registered using the
addActionListener() method. When the action event occurs, that object's actionPerformed
method is invoked.

10 | P a g e
Interface declaration

Following is the declaration for java.awt.event.ActionListener interface:

public interface ActionListener


extends EventListener

void actionPerformed(ActionEvent e)

Invoked when an action occurs.

AdjustmentListener

Introduction
The interfaceAdjustmentListener is used for receiving adjustment events. The class that process
adjustment events needs to implements this interface.
Class declaration
Following is the declaration for java.awt.event.AdjustmentListener interface:
public interface AdjustmentListener
extends EventListener
Interface methods

S.N. Method & Description

1 void adjustmentValueChanged(AdjustmentEvent e)
Invoked when the value of the adjustable has changed.

Working with ContainerListener

The interfaceContainerListener is used for receiving container events. The class that process
container events needs to implements this interface.
Class declaration
Following is the declaration for java.awt.event.ContainerListener interface:
public interface ContainerListener
extends EventListener

11 | P a g e
Interface methods

S.N. Method & Description

1 void componentAdded(ContainerEvent e)
Invoked when a component has been added to the container.

2 void componentRemoved(ContainerEvent e)
Invoked when a component has been removed from the container.

ItemListener

The class which processes the ItemEvent should implement this interface.The object of that class
must be registered with a component. The object can be registered using the addItemListener()
method. When the action event occurs, that object's itemStateChanged method is invoked.
Interface declaration
Following is the declaration for java.awt.event.ItemListener interface:
public interface ItemListener
extends EventListener
Interface methods

S.N. Method & Description

1 void itemStateChanged(ItemEvent e)
Invoked when an item has been selected or deselected by the user.

ComponentListener

The class which processes the ComponentEvent should implement this interface.The object of
that class must be registered with a component. The object can be registered using the
addComponentListener() method. Component event are raised for information only.
Interface declaration
Following is the declaration for java.awt.event.ComponentListener interface:
public interface ComponentListener
extends EventListener

12 | P a g e
Interface methods

S.N. Method & Description

1 void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.

2 void componentMoved(ComponentEvent e)
Invoked when the component's position changes.

3 void componentResized(ComponentEvent e)
Invoked when the component's size changes.

4 void componentShown(ComponentEvent e)
Invoked when the component has been made visible.

Working with KeyListener

The class which processes the KeyEvent should implement this interface.The object of that class
must be registered with a component. The object can be registered using the addKeyListener()
method.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
public interface KeyListener
extends EventListener
Interface methods

S.N. Method & Description

1 void keyPressed(KeyEvent e)
Invoked when a key has been pressed.

2 void keyReleased(KeyEvent e)
Invoked when a key has been released.

3 void keyTyped(KeyEvent e)

13 | P a g e
Invoked when a key has been typed.

MouseListener

The class which processes the MouseEvent should implement this interface.The object of that
class must be registered with a component. The object can be registered using the
addMouseListener() method.
Interface declaration
Following is the declaration for java.awt.event.MouseListener interface:
public interface MouseListener
extends EventListener
Interface methods

S.N. Method & Description

1 void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a
component.

2 void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.

3 void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.

4 void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.

5 void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.

Introduction AWT Controls

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

14 | P a g e
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).

The hierarchy of Java AWT classes are given below.

Working with Label controls

Label class is a component for placing text in a container. It is used to display a single line
of read only text. The text can be changed by a programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a label,
we need to create the object of Label class.

15 | P a g e
Constructors

1. Label() It constructs an empty label.

2. Label(String text) It constructs a label with the given string (left justified by default).

3. Label(String text, int It constructs a label with the specified string and the specified
alignement) alignment.

Methods

1. void setText(String text) It sets the texts for label with the specified text.

2. void setAlignment(int alignment) It sets the alignment for label with the specified
alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

5. void addNotify() It creates the peer for the label.

6. AccessibleContext It gets the Accessible Context associated with the label.


getAccessibleContext()

7. protected String paramString() It returns the string the state of the label.

Example

import java.awt.*;

public class LabelExample {


public static void main(String args[]){

// creating the object of Frame class and Label class

16 | P a g e
Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output

17 | P a g e
Working with Buttons controls

The Button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. When we press a button and
release it, AWT sends an instance of ActionEvent to that button by calling processEvent on the
button.

To perform an action on a button being pressed and released, the ActionListener interface needs
to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button.
Button Class Constructors

1. Button( ) It constructs a new button with an empty string i.e. it has no label.

2. Button (String text) It constructs a new button with given string as its label.

Methods

1. void setText (String text) It sets the string message on the button

2. String getText() It fetches the String message on the button.

3. void setLabel (String label) It sets the label of button with the specified string.

4. String getLabel() It fetches the label of the button.

5. void addNotify() It creates the peer of the button.

6. AccessibleContext It fetched the accessible context associated with the


getAccessibleContext() button.

7. void It adds the specified action listener to get the action


addActionListener(ActionListener l) events from the button.

8. String getActionCommand() It returns the command name of the action event fired
by the button.

18 | P a g e
9. ActionListener[ ] getActionListeners() It returns an array of all the action listeners registered
on the button.

Example

import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output

19 | P a g e
Working with CheckBoxes

The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".

Constructrs

1. Checkbox() It constructs a checkbox with no string as the label.

2. Checkbox(String label) It constructs a checkbox with the given label.

3. Checkbox(String label, boolean It constructs a checkbox with the given label and sets
state) the given state.

Methods

void addItemListener(ItemListener It adds the given item listener to get the item events from
IL) the checkbox.

void addNotify() It creates the peer of checkbox.

ItemListener[] getItemListeners() It returns an array of the item listeners registered on


checkbox.

String getLabel() It fetched the label of checkbox.

Object[] getSelectedObjects() It returns an array (size 1) containing checkbox label and


returns null if checkbox is not selected.

20 | P a g e
boolean getState() It returns true if the checkbox is on, else returns off.

void It removes the specified item listener so that the item


removeItemListener(ItemListener l) listener doesn't receive item events from the checkbox
anymore.

void setLabel(String label) It sets the checkbox's label to the string argument.

void setState(boolean state) It sets the state of checkbox to the specified state.

Example

Working with CheckBoxGroup controls

CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box
button is allowed to be in "on" state and remaining check box button in "off" state.

Working with Choice controls

Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of a menu. It inherits Component class.

Constructor

Choice() It constructs a new choice menu.

Example

21 | P a g e
Working with Lists controls

List class represents a list of text items. With the help of the List class, user can choose either
one item or multiple items. It inherits the Component class.

Constructors

1. List() It constructs a new scrolling list.

2. List(int row_num) It constructs a new scrolling list initialized with the given
number of rows visible.

3. List(int row_num, Boolean It constructs a new scrolling list initialized which displays
multipleMode) the given number of rows.

Some of the methods are

1. void add(String item) It adds the specified item into the end of scrolling list.

2. void add(String item, int index) It adds the specified item into list at the given index
position.

3. void addActionListener(ActionListener It adds the specified action listener to receive action events
l) from list.

22 | P a g e
4. void addItemListener(ItemListener l) It adds specified item listener to receive item events from
list.

Example

Working with TextField controls

TextField class is a text component that allows a user to enter a single line text and edit it. It
inherits TextComponent class, which further inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed), the event is
sent to TextField. Then the KeyEvent is passed to the registered KeyListener.

constructors

1. TextField() It constructs a new text field component.

2. TextField(String text) It constructs a new text field initialized with the given string text
to be displayed.

3. TextField(int columns) It constructs a new textfield (empty) with given number of


columns.

4. TextField(String text, int It constructs a new text field with the given text and given

23 | P a g e
columns) number of columns (width).

Output

Introduction to Layout Manager

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is


an interface that is implemented by all the classes of layout managers.

There are following classes that represents the layout managers:


1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout

FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.

import java.awt.*;
class FlowLayoutExample extends Frame
{
FlowLayoutExample()
{
Button[] button =new Button[10];
setLayout(new FlowLayout());
for(int i=0;i<button.length;i++)

24 | P a g e
{
button[i]=new Button("Button "+(i+1));
add(button[i]);
}
}
}
class FlowLayoutJavaExample
{
public static void main(String args[])
{
FlowLayoutExample frame = new FlowLayoutExample();
frame.setTitle("FlowLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}

BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window.

import java.awt.*;
class BorderLayoutExample extends Frame
{
BorderLayoutExample()
{
setLayout(new BorderLayout());
add(new Button("NORTH"),BorderLayout.NORTH);
add(new Button("SOUTH"),BorderLayout.SOUTH);
add(new Button("EAST"),BorderLayout.EAST);
add(new Button("WEST"),BorderLayout.WEST);
add(new Button("CENTER"),BorderLayout.CENTER);
}

25 | P a g e
}
class BorderLayoutJavaExample
{
public static void main(String args[])
{
BorderLayoutExample frame = new BorderLayoutExample();
frame.setTitle("BorderLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}

GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.

import java.awt.*;
class GridLayoutExample extends Frame
{
GridLayoutExample()
{
Button[] button =new Button[12];
setLayout(new GridLayout(4,3));
for(int i=0; i<button.length;i++)
{
button[i]=new Button("Button "+(i+i));
add(button[i]);
}
}}
class GridLayoutJavaExample
{
public static void main(String args[])
{
GridLayoutExample frame = new GridLayoutExample();
frame.setTitle("GridLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);

26 | P a g e
}
}

Introduction to I/O Streams

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

27 | P a g e
OutputStream Hierarchy

InputStream Hierarchy

Byte Streams classes

28 | P a g e
ByteStream classes are used to read bytes from the input stream and write bytes to the output
stream. In other words, we can say that ByteStream classes read/write the data of 8-bits. We can
store video, audio, characters, etc., by using ByteStream classes. These classes are part of the
java.io package.

The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the Input/Output stream
classes

Character Streams classes

CharacterStream classes are mainly used to read characters from the source and write them to the
destination. For this purpose, the CharacterStream classes are divided into two types of classes,
I.e., Reader class and Writer class.

Reader Class

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char array.

3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the underlying
character input stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

6 PipedReader This class provides methods to read characters from the connected
piped output stream.

7 StringReader This class provides methods to read characters from a string.

29 | P a g e
Writer Class

1 BufferedWriter This class provides methods to write characters to the buffer.

2 FileWriter This class provides methods to write characters to the file.

3 CharArrayWriter This class provides methods to write the characters to the character array.

4 OutpuStreamWriter This class provides methods to convert from bytes to characters.

5 PipedWriter This class provides methods to write the characters to the piped output stream.

6 StringWriter This class provides methods to write the characters to the string.

30 | P a g e

You might also like