0% found this document useful (0 votes)
15 views138 pages

Java Event Handling in GUI Applications

The document provides an overview of event handling in Java, emphasizing its importance for creating interactive GUI applications. It explains the Delegation Event Model, which involves event sources, event objects, and event listeners, along with common event classes and their functionalities. Additionally, it covers key concepts such as registering listeners, handling keyboard and mouse events, and the hierarchy of GUI components in Java AWT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views138 pages

Java Event Handling in GUI Applications

The document provides an overview of event handling in Java, emphasizing its importance for creating interactive GUI applications. It explains the Delegation Event Model, which involves event sources, event objects, and event listeners, along with common event classes and their functionalities. Additionally, it covers key concepts such as registering listeners, handling keyboard and mouse events, and the hierarchy of GUI components in Java AWT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Object Oriented

Programming using Java


II BSC
Event Handling
• Event handling is the process of detecting an event (like a button click,
mouse movement, key press) and responding to it.
• It is essential for making interactive GUI applications in Java.
• Without it, user input wouldn't trigger any response.
• There are several types of events,including those generated by the
mouse,the keyboard and various controls such as a pushbutton,
• AWT(Abstract Window Toolkit) based events are supported by the
[Link] package.
import [Link].*; import [Link].*;

This imports all classes from the This imports all classes from
[Link] package, such as: the [Link] package,
such as:
•Frame
•Button •ActionEvent
•Label •ActionListener
•TextField •MouseEvent
•Checkbox •MouseListener
•Panel •KeyEvent
•and other GUI components. •WindowEvent
•ItemEvent
•and more...
Delegation Event Model

• The Delegation Event Model in Java is a way to


handle events where an event source sends an event
to an event listener that processes it.
• Three key participants:
• Event source (e.g., a button)
• Event object (contains event details)
• Event listener (handles the event)
Events
• An event is an object that describes an action like clicking
a button, pressing a key, moving the mouse, etc.
• In Java GUI programming (AWT or Swing), user actions such
as:
• Clicking a button
• Typing in a text field
• Selecting an item from a menu
• Moving the mouse
• These events are:
• Generated by the source (e.g., button)
• Captured by the listener (e.g., code that runs on click)
• Handled using methods (e.g., actionPerformed())
Example Real-Life Analogy
Imagine a doorbell system:
• Pressing the bell = Event generated
• Bell (device) = Event source
• Person inside the house = Listener
• Person opens the door = Event handled
Key Components of an Event

Component Description
Event Class Represents the actual event (e.g.,
ActionEvent, MouseEvent)
Event The object/component that generates the
Source event (e.g., Button, TextField)
Event The object that receives and handles the
Listener event (e.g., class implementing
ActionListener)
[Link] Source
• An event source is the object (typically a GUI
component) that generates an event when a user
interacts with it.
• A source must register listeners in order for the listener
to receive notification about specific type of event.
• Examples:
•Button (Button) – when clicked
•TextField (TextField) – when text changes or key is typed
•ScrollBar (ScrollBar) – when it is moved
•Window (Frame, JFrame) – when it is opened, closed, minimized
Registering a Listener:
public void addTypeListener(TypeListener el)
•Type = event type (e.g., Key, Mouse)
•el = event listener object

Examples:
•addKeyListener() → registers key listener
•addMouseListener() → registers mouse listener

Removing Listener:
public void removeTypeListener(TypeListener el)
[Link] Listener

• An event listener is an object that is notified when an


event occurs.
• It is responsible for handling events like mouse clicks, key
presses, etc.
Requirements:
1. Must Implement an Event Listener Interface
A listener must implement a predefined interface from
the [Link] package (or [Link] in
Swing).
[Link] Be Registered with an Event Source
A listener will not receive any events unless it is explicitly
registered with an event source.
How It Works
1.A listener must register with an event source using a
method like addTypeListener().
[Link] must implement a specific interface based on the event
type.
[Link] the event occurs, the source calls the method inside
the listener to handle it.

General Syntax for Adding a Listener:


• [Link](TypeListener el);
[Link] Classes
• Event classes are special Java classes that store information about something that
happened, like:
•A button was clicked
•A key was pressed
•The mouse was moved
•A window was closed
• When the user does something, Java creates an event object (from an event class) and sends it to the listener (the part
of your program that reacts).
• When the user does something, Java creates an event object (from an event class) and sends it to the listener (the part
of your program that reacts).
• At the root of the Java event class hierarchy is EventObject, which is in [Link] superclass for all events.
• Its one constructor is shown here:
• EventObject(Object src)
• Here, src is the object that generates this event.
• EventObject contains two methods:
• getSource( ) and toString( ).
• The getSource( ) method returns the source of the event. Its general form is shown here: Object getSource( ) As
expected, toString( ) returns the string equivalent of the event
Commonly Used Event Classes in
[Link]
Event Class What It Represents

ActionEvent Occurs when a button is clicked or menu item is selected

ItemEvent Occurs when a checkbox, list item, or choice is


selected/deselected
KeyEvent Occurs when a keyboard key is pressed, released, or typed

MouseEvent Occurs when the mouse is clicked, pressed, released,


moved, or dragged
MouseWheelEv Occurs when the mouse wheel is moved
ent
WindowEvent Occurs when a window is opened, closed, minimized, or
activated
FocusEvent Occurs when a component gains or loses keyboard focus

TextEvent Occurs when the value of a text field or text area is


changed
AdjustmentEve Occurs when a scrollbar is adjusted
nt
ContainerEvent Occurs when a component is added to or removed from a
Frame
• A Frame is a top-level window with a title bar, borders, and a
close/minimize button.
• Frame f = new Frame("My First Frame");
FlowLayout
• In Java AWT, Frame is a top-level container that can use layout
managers to arrange its components (like buttons, labels, etc.).
• [Link](new FlowLayout());
setSize
• This sets the size of the window (Frame).
• [Link](int width, int height);
setVisible
• true to show the frame, false to hide it
• [Link](true);
add
• [Link](Component c);
• Eg: Button b = new Button("Click Me");
The KeyEvent Class
• A KeyEvent is generated when a keyboard key is pressed, released, or typed in
a Java program.
• Types of Key Events
•KEY_PRESSED → Triggered when a key is pressed down.
•KEY_RELEASED → Triggered when a key is released.
•KEY_TYPED → Triggered when a key generates a character (only happens
for character-producing keys).

• Important Notes
• Not all key presses produce characters
• Example: Shift, Ctrl, Alt do not generate KEY_TYPED.
• Example: Pressing Shift alone → KEY_PRESSED and KEY_RELEASED
happen, but no KEY_TYPED.
• Key Codes
•Each key has a constant value in KeyEvent called a Virtual Key Code
(VK codes).
•Examples:
•VK_A → Key 'A'
•VK_0 → Key '0'
•VK_ENTER → Enter key
•VK_LEFT, VK_RIGHT → Arrow keys
•VK_SHIFT, VK_CONTROL, VK_ALT → Modifier keys.

• VK Constants
•VK_0 to VK_9 → Number keys (0–9).
•VK_A to VK_Z → Alphabet keys (A–Z).
•Special keys: VK_ENTER, VK_ESCAPE, VK_PAGE_UP, etc.
•Independent of modifiers like Ctrl, Shift, or Alt.
•Getting Key Names
•[Link](int keyCode) → Returns the readable
name of a key code.
Example: [Link](KeyEvent.VK_A) → "A".

•Usage
•Typically used with KeyListener or KeyAdapter interfaces
to handle keyboard input in GUI programs
import [Link].*; public void keyPressed(KeyEvent e) {
import [Link].*; [Link]("Key Pressed: " +
[Link]([Link]()));
}
public class SimpleKeyEvent extends Frame
implements KeyListener {
public void keyReleased(KeyEvent e) {
Label label; [Link]("Key Released: " +
[Link]([Link]()));
}
public SimpleKeyEvent() {
label = new Label("Press any key...");
public void keyTyped(KeyEvent e) {
[Link](new Font("Arial", [Link],
18)); [Link]("Key Typed: " + [Link]());
add(label); }

addKeyListener(this); public static void main(String[] args) {


setSize(400, 200); new SimpleKeyEvent();
setLayout(new FlowLayout()); }
setVisible(true); }
}
Concept In Program Explanation
Key pressed, key released, or key The action performed by the user
Event
typed (keyboard interaction).
Contains details about the
Event Class KeyEvent keyboard action (key code, key
char, etc.).
The Frame object created by new
The object where the event
Event Source SimpleKeyEvent() — it generates
originates.
the KeyEvents.
The interface your class
Event Listener KeyListener implements to listen for keyboard
events.
The methods that run when the
keyPressed(KeyEvent e),
specific event happens; they
Event Handlers keyReleased(KeyEvent e),
contain the code that updates the
keyTyped(KeyEvent e)
label.
MouseEvent Class
•A MouseEvent occurs when the mouse interacts with a
component.
•Examples: clicking, pressing, moving, dragging, entering, or
exiting an area.
•MouseEvent is a subclass of InputEvent.
•Types of Mouse Events (Constants)
Constant Description
MOUSE_CLICKED Mouse clicked.
MOUSE_DRAGGED Mouse dragged.
MOUSE_ENTERED Mouse entered a component.
MOUSE_EXITED Mouse exited a component.
MOUSE_MOVED Mouse moved.
MOUSE_PRESSED Mouse pressed.
MOUSE_RELEASED Mouse released.
MOUSE_WHEEL Mouse wheel moved.
• Constructor
• MouseEvent(Component src, int type, long when, int modifiers,int x, int y,
int clicks, boolean triggersPopup)
•src → Component that generated the event.
•type → Type of event (clicked, moved, etc.).
•when → Time of the event.
•modifiers → Modifier keys pressed (Shift, Ctrl, etc.).
•x, y → Coordinates relative to component.
•clicks → Number of mouse clicks.
•TriggersPopup → true if popup menu is triggered.
• Common Methods
•getX() / getY() → X and Y coordinates within the component.
•getPoint() → Returns coordinates as a Point object.
•translatePoint(int x, int y) → Moves the event location.
•getClickCount() → Number of clicks.
•isPopupTrigger() → Checks if popup menu should show.
•getButton() → Returns mouse button (BUTTON1, BUTTON2, BUTTON3, NOBUTTON).
•getLocationOnScreen() → Point object with screen coordinates.
•getXOnScreen() / getYOnScreen() → Coordinates relative to screen.
• Mouse Button Constants
•NOBUTTON → No button
pressed.
•BUTTON1 → Usually left click.
•BUTTON2 → Middle click.
•BUTTON3 → Right click.
import [Link].*;
import [Link].*; // MouseListener methods // MouseMotionListener methods
public void mouseClicked(MouseEvent e) { public void mouseDragged(MouseEvent e) {
public class SimpleMouseEventExample extends Frame [Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]("Mouse Dragged at (" + [Link]() + ", "
implements MouseListener, MouseMotionListener { [Link]() + ")"); + [Link]() + ")");
} }
Label label;
public void mousePressed(MouseEvent e) { public void mouseMoved(MouseEvent e) {
SimpleMouseEventExample() { [Link]("Mouse Pressed"); [Link]("Mouse Moved at (" + [Link]() + ", " +
[Link]() + ")");
label = new Label("Interact with the mouse inside }
the window"); }
[Link](50, 50, 300, 30);
public void mouseReleased(MouseEvent e) {
public static void main(String[] args) {
[Link]("Mouse Released");
add(label); new SimpleMouseEventExample();
}
setSize(400, 300); }
setLayout(null); }
public void mouseEntered(MouseEvent e) {
setVisible(true);
[Link]("Mouse Entered");
}
// Add mouse listeners
addMouseListener(this);
public void mouseExited(MouseEvent e) {
addMouseMotionListener(this);
[Link]("Mouse Exited");
}
}
MouseWheelEvent Class
[Link]: Encapsulates a mouse wheel event.
[Link]: Subclass of MouseEvent.
[Link] Wheel Location:
•Not all mice have wheels.
•If present, the wheel is between the left and right buttons.
•Primarily used for scrolling.
[Link] Defined:
•WHEEL_BLOCK_SCROLL: Page-up or page-down scroll
event.
•WHEEL_UNIT_SCROLL: Line-up or line-down scroll event.
Constructor
• MouseWheelEvent(Component src, int type, long when, int modifiers,int x,
int y, int clicks, boolean triggersPopup,int scrollHow, int amount, int count)

•src – Reference to object generating the event.


•type – Type of the event.
•when – System time when the event occurred.
•modifiers – Which modifier keys were pressed during the event.
•x, y – Coordinates of the mouse.
•clicks – Number of wheel rotations (clicks).
•triggersPopup – Boolean indicating if event triggers a pop-up menu.
•scrollHow – Type of scroll (WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL).
•amount – Number of units to scroll.
•count – Number of rotational units moved by the wheel.
Methods
[Link] getWheelRotation()
• Returns number of rotational units.
• Positive value → wheel moved
counterclockwise.
• Negative value → wheel moved clockwise.
[Link] getScrollType()
• Returns scroll type:
• WHEEL_UNIT_SCROLL
• WHEEL_BLOCK_SCROLL
[Link] getScrollAmount()
• Returns number of units to scroll.
• Only applicable if getScrollType() returns
WHEEL_UNIT_SCROLL.
InWindow Fundamentals
Java AWT, windows are not just a single class — they
are built step by step in a class hierarchy. Each class
adds more power and features.
The two most commonly used types of windows are:
[Link] → Used inside applets (or other containers).
•A Panel is like a blank board where you can draw something
or add controls (buttons, text fields, etc.).
•It cannot exist on its own (it must be inside another
window).
[Link] → A top-level window (like a standard application
window).
•A Frame has a title bar, borders, buttons (minimize,
maximize, close).
•It can exist independently and is commonly used in desktop
applications.
Class hierarchy for Panel and Frame
1. Component ([Link])
•Top of AWT hierarchy.
•Abstract class that defines all attributes of a GUI element.
•All UI elements (Button, Label, TextField, etc.) are subclasses of
Component.
•Defines 100+ methods for:
•Handling events (mouse, keyboard, focus).
•Setting size and position (setSize(), setBounds()).
•Repainting (repaint()).
•Managing foreground & background colors.
•Managing font.
2. Container ([Link])
• Subclass of Component.
• Special component → can hold other components.
• Allows nesting (a container can hold other containers).
• Responsible for layout of components using layout managers.
3. Panel ([Link])
•Subclass of Container.
•A concrete class (not abstract).
•Behaves like a window without a title bar, menu bar, or border.
•Superclass of Applet → Applet’s output is drawn on a Panel.
•Components can be added using add().
•Size and position can be set using methods inherited from Component
(setLocation(), setSize(), setBounds()).
• A Panel is not a top-level window → it must be inside another
container like a Frame.

4. Window ([Link])
•Subclass of Container.
•A top-level window → not contained in another object, sits directly
on the desktop.
•Usually not created directly.
•Instead, you use subclasses like Frame or Dialog.
5. Frame ([Link])
•Subclass of Window.
•Represents a standard application window with:
•Title bar
•Menu bar
•Borders
•Resizing corners
•If created from an applet, the Frame shows a warning message
(“Java Applet Window”) to alert users.
•If created from a standalone application, it shows a normal
window.
6. Canvas ([Link])
• Not part of the Panel/Frame hierarchy but important.
• Provides a blank window area on which you can draw shapes,
images, or graphics.
• Commonly used for custom graphics or game development in
AWT.
Layout Manager
• A layout manager automatically arranges components inside a container (like
a window or panel).
• It uses an algorithm to decide positions and sizes.
• Every Container (like JFrame, JPanel) has a layout manager.
• Set with:
void setLayout(LayoutManager layoutObj)
o If not set → default layout manager is used.
o If null is passed → Layout Manager is disabled → must manually set
positions using setBounds()
Responsibilities of Layout Manager
• Keeps track of all components added to a container.
• Decides placement & size when container is resized or displayed.
• Uses:
• minimumLayoutSize()
• preferredLayoutSize()
• Each component provides:
• getPreferredSize()
• getMinimumSize()
Customization:
•You can override size methods if creating custom components.
•Default values exist otherwise.

Predefined Layout Managers in Java:


•Java provides several built-in managers
•Choose based on your application’s needs.

Layout Managers are:


1. FlowLayout
2. BorderLayout
3. GridLayout
[Link]
Definition:
• The simplest layout manager.
• Components are placed like words in a text editor: left → right, top
bottom.
• When a row is full → moves to the next line.
Default Behavior:
• Starts from upper-left corner.
• Leaves a small gap (5 pixels by default) between components on all
• Orientation: Left to Right, Top to Bottom (can be changed using
component orientation).
Constructors:
• FlowLayout()
• FlowLayout(int how)
• FlowLayout(int how, int horz, int vert)

• First form: Default → center alignment, 5px horizontal + vertical gap.


• Second form: Lets you specify alignment.
• Third form: Lets you specify alignment + gaps (horizontal, vertical).
Alignment Options (int how):
• [Link] → Align left.
• [Link] → Align center (default).
• [Link] → Align right.
• [Link] → Align to leading edge (depends on
component orientation, e.g., left in LTR languages).
• [Link] → Align to trailing edge (e.g., right in LTR
languages).
import [Link]; add(new Button("Two"));
import [Link].*; add(new Button("Three"));
add(new Button("Four"));
/* }
<applet code="SimpleFlowLayoutApplet" }
width=250 height=150>
}
</applet>
*/

public class SimpleFlowLayoutApplet extends


Applet {
public void init() {
public void init() {
// FlowLayout with LEFT alignment
setLayout(new FlowLayout([Link]));

add(new Button("One"));
[Link]
• A layout manager with five regions:
• NORTH (top)
• SOUTH (bottom)
• EAST (right)
• WEST (left)
• CENTER (middle → expands to fill space).
Constructors
• BorderLayout()
• BorderLayout(int horz, int vert)
First form: Default layout, no extra spacing.
Second form: Lets you specify horizontal and vertical gaps between components
Constants (Regions)
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
Adding Components
void add(Component comp, Object region)
• comp → the component to add.
• region → one of the constants (NORTH, SOUTH, EAST,
WEST, CENTER).
Rules
•Only one component per region.
•If multiple are added to the same region, the last one replaces
the earlier.
•CENTER grows to occupy all remaining space.
import [Link]; add(new Label("The footer message might
go here."), [Link]);
import [Link].*;
add(new Button("Right"),
[Link]);
/*
add(new Button("Left"),
<applet code="BorderLayoutDemo" width=400 [Link]);
height=200>
</applet>
// Center text area with a quote
*/
String msg = "The reasonable man adapts
himself to the world"
public class BorderLayoutDemo extends Applet add(new TextArea(msg), [Link]);
{
}
public void init() {
}
// Use BorderLayout with default gaps
setLayout(new BorderLayout());

// Add components to each region


add(new Button("This is across the top."),
[Link]);
[Link]
• Arranges components in a grid of rows × columns.
• All cells are the same size.
Constructors:
• GridLayout() // 1 column
by default
• GridLayout(int rows, int cols) // specify
rows & cols
• GridLayout(int rows, int cols, int h, int v) // with
gaps
• If you set rows = 0, columns are unlimited.
• If you set cols = 0, rows are unlimited.
import [Link];
import [Link].*; // Fill the grid with buttons labeled 1 to
15
for (int i = 1; i < n * n; i++) {
/*
<applet code="GridLayoutDemo" add(new Button("" + i));
width=300 height=200> }
</applet> }
*/ }

public class GridLayoutDemo extends Applet


{
static final int n = 4; // 4x4 grid

public void init() {


setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif",
[Link], 18));
Control Fundamentals

• The AWT supports the following types of controls:


• Labels
• Push buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing
These controls are subclasses of Component
Adding and Removing Controls
• To include a control in a window, you must add it to the
window. To do this, you must first create an instance of the
desired control and then add it to a window by calling add(),
which is defined by Container.
• Its general form:
• Component add(Component compObj)
• Here, compObj is an instance of the control that you want to add. A
reference to compObj is returned. Once a control has been added, it will
automatically be visible whenever its parent window is displayed.

• Sometimes you will want to remove a control from a window


when the control is no longer needed. To do this, call remove().
This method is also defined by Container. It has this general
form:
• void remove(Component obj)
• Here, obj is a reference to the control you want to remove.
• You can remove all controls by calling removeAll().
Labels
• Label is a passive GUI control in Java (from [Link]), used to display text.
• It does not interact with the user—just shows information.

Label Constructors
[Link]()
•Creates a blank label.

[Link](String str)
•Creates a label containing the string str.
•Default alignment: left-justified.

[Link](String str, int how)


•Creates a label with text str and alignment how.
•Alignment options:
•[Link]
•[Link]
•[Link]
Label Methods
[Link] or get text
•void setText(String str) → changes the label’s text.
•String getText() → returns the current text.
[Link] or get alignment
•void setAlignment(int how) → changes text alignment.
•int getAlignment() → returns current alignment.
import [Link].*; Label("Three");
import [Link].*;
// Add labels to applet window
/* add(one);
<applet code="LabelDemo" add(two);
width=300 height=200> add(three);
</applet> }
*/ }

public class LabelDemo extends


Applet {
public void init() {
Label one = new Label("One"); What happens:
Label two = new Label("Two"); • Three labels (One, Two, Three) are displayed.
• The default layout manager arranges them
Label three = new automatically.
Button
• Button is a clickable GUI control in Java ([Link]).
• A button displays a label and generates an event when pressed.

Button Constructors
1. Button() – creates an empty button.
2. Button(String str) – creates a button with label str.

Button Methods
[Link] or get the label
•void setLabel(String str) → sets a new label.
•String getLabel() → returns the current label.
[Link] or get the action command
•void setActionCommand(String str) → sets a custom action
command (does not change the label).
•By default, the action command is the button’s label.
Handling Button Clicks
• Each click generates an ActionEvent.
• Components that handle this implement ActionListener.
• The actionPerformed(ActionEvent ae) method is called when the
button is pressed.
• Use [Link]() or [Link]() to determine which
button was clicked:
• By label: [Link]() (default is the button’s label).
• By object reference: [Link]() == buttonObject.
// Demonstrate Buttons
import [Link].*; add(yes); add(no); add(maybe);
import [Link].*;
import [Link].*; [Link](this);
[Link](this);
/* [Link](this);
<applet code="ButtonDemo" width=250 height=150> }
</applet>
*/ public void actionPerformed(ActionEvent ae) {
public class ButtonDemo extends Applet implements msg = "You pressed " + [Link]();
ActionListener {
repaint();
String msg = ""; }
Button yes, no, maybe;

public void paint(Graphics g) {


public void init() {
[Link](msg, 20, 100);
yes = new Button("Yes"); }
no = new Button("No");
}
// Recognize Button objects. bList[2] = (Button) add(maybe);
import [Link].*;
import [Link].*; // register to receive action events
import [Link].*; for (int i = 0; i < 3; i++) {
bList[i].addActionListener(this);
/* }
<applet code="ButtonList" width=250 height=150> }
</applet>
*/ public void actionPerformed(ActionEvent ae) {
for (int i = 0; i < 3; i++) {
public class ButtonList extends Applet implements ActionListener if ([Link]() == bList[i]) {
{
msg = "You pressed " + bList[i].getLabel();
String msg = "";
}
Button bList[] = new Button[3];
}
repaint(); // refresh the applet so paint() is called
public void init() {
}
Button yes = new Button("Yes");
Button no = new Button("No");
public void paint(Graphics g) {
Button maybe = new Button("Undecided");
[Link](msg, 6, 100);
}
// store references to buttons as they are added
}
bList[0] = (Button) add(yes);
bList[1] = (Button) add(no);
Checkbox
• A checkbox is a GUI control that lets you turn an option ON/OFF.
• It can be checked (true) or unchecked (false).
• Each checkbox has:
• A label (e.g., "Windows XP")
• A state (true = checked, false = unchecked)
• Checkboxes can be used:
• Individually → multiple can be selected.
• As part of a group → only one can be selected (CheckboxGroup).
• Checkboxes are objects of the Checkbox class.

Methods Method Description


boolean getState() Returns true if the checkbox is checked, else false.
void setState(boolean
Sets the checkbox state. true → checked, false → unchecked.
on)
String getLabel() Returns the current label of the checkbox.
void setLabel(String str) Sets a new label for the checkbox.
Events with Checkbox
• When a checkbox is checked/unchecked → an ItemEvent is generated.
• To handle it, you must implement ItemListener.
• Method:
public void itemStateChanged(ItemEvent ie)
This is called automatically whenever checkbox state changes.

Constructor Description
Creates a checkbox with no label. The initial state is
Checkbox()
unchecked.

Checkbox(String str) Creates a checkbox with label str. The initial state is unchecked.

Creates a checkbox with label str. If on = true, the checkbox is


Checkbox(String str, boolean on)
initially checked; otherwise, it is unchecked.

Creates a checkbox with label str, belonging to the specified


Checkbox(String str, boolean on, CheckboxGroup cbGroup)
group cbGroup. Initial state is checked if on = true.

Same as above but with different parameter order. Associates


Checkbox(String str, CheckboxGroup cbGroup, boolean on)
the checkbox with cbGroup. Initial state depends on on.
// Simple Checkbox Example add(python);
import [Link].*;
import [Link].*; // register listeners
import [Link].*; [Link](this);
[Link](this);
/* }
<applet code="SimpleCheckbox" width=250 height=150>
</applet> // runs when a checkbox is clicked
*/ public void itemStateChanged(ItemEvent ie) {
repaint(); // update screen
public class SimpleCheckbox extends Applet implements }
ItemListener {
String msg = "";
// display current state
Checkbox java, python;
public void paint(Graphics g) {
msg = "Java: " + [Link]();
public void init() {
[Link](msg, 6, 80);
// create checkboxes
java = new Checkbox("Java");
msg = "Python: " + [Link]();
python = new Checkbox("Python", true); // initially checked
[Link](msg, 6, 100);
}
// add to applet
}
add(java);
CheckboxGroup (Radio Buttons)
• A CheckboxGroup allows you to create a set of mutually exclusive checkboxes.
• Only one checkbox in the group can be selected at any time.
• These checkboxes behave like radio buttons (like a car radio selector — only one station
can be active).
How to use a CheckboxGroup
• Create the group first using the default constructor:
• CheckboxGroup cbg = new CheckboxGroup();
This creates an empty group.
• Create checkboxes and assign them to the group:
• Checkbox winXP = new Checkbox("Windows XP", cbg, true); // selected by default
• Checkbox winVista = new Checkbox("Windows Vista", cbg, false);
Method Description
Checkbox getSelectedCheckbox() Returns the checkbox currently selected in the group.
Selects the checkbox which in the group. The previously selected
void setSelectedCheckbox(Checkbox which)
checkbox is deselected automatically.
// CheckboxGroup Example (Radio Buttons) female = new Checkbox("Female", group, false);
import [Link].*;
import [Link].*; // add to applet
import [Link].*; add(male);
add(female);
/*
<applet code="RadioButtonDemo" width=250 height=150> // register listeners
</applet> [Link](this);
*/ [Link](this);
}
public class RadioButtonDemo extends Applet implements ItemListener {
String msg = ""; public void itemStateChanged(ItemEvent ie) {
CheckboxGroup group; repaint(); // update screen
Checkbox male, female; }

public void init() { public void paint(Graphics g) {


// create group msg = "Selected: " + [Link]().getLabel();
group = new CheckboxGroup(); [Link](msg, 6, 100);
}
// create checkboxes that belong to the group (radio buttons) }
male = new Checkbox("Male", group, true); // selected by default
TextField
• TextField is a single-line editable text input component in Java
AWT ([Link]). Used for forms (e.g.,
username/password).
• Subclass of TextComponent (inherits from Component).
• Key Features:
• User can type/edit text using keyboard/mouse.
• Supports selection, password mode (hide chars), and Enter key events.
• Platform-dependent look (e.g., different on Windows/Linux).
• Importance: Simple for beginner GUIs; handles input
securely without complex setup. Use in applets/frames for
forms. (For multi-line, use TextArea.)
Constructors
Constructor Description

TextField() Default empty field (width ~10 cols)

TextField(int columns) Empty field with given width

TextField(String text) Pre-filled with text (default width)

TextField(String text, int columns) Pre-filled + width


Methods
Method Description
String getText() Returns the current text in the text field.
void setText(String str) Sets new text into the text field.
String getSelectedText() Returns the text that is currently selected.
void select(int startIndex, int endIndex) Selects the text from startIndex to endIndex-1.

boolean isEditable() Returns true if the text field is editable, otherwise false.

void setEditable(boolean canEdit) Makes the text field editable (true) or read-only (false).

void setEchoChar(char ch) Sets a character (like * or ?) to mask input (useful for passwords).

boolean echoCharIsSet() Returns true if echo character is set.


char getEchoChar() Returns the echo character currently being used.
import [Link];
import [Link].*; // Add components to Applet
import [Link].*; add(lblName); add(name);
add(lblPass); add(pass);
/*
<applet code="SimpleTextFieldApplet" width=350
height=150> // Register listeners
</applet> [Link](this);
*/ [Link](this);
}
public class SimpleTextFieldApplet extends Applet implements
ActionListener {
TextField name, pass; // Called when ENTER is pressed

String msg = ""; public void actionPerformed(ActionEvent ae) {

public void init() { msg = "Name: " + [Link]() +

// Create Labels " Password: " + [Link]();

Label lblName = new Label("Name: ", [Link]); repaint();

Label lblPass = new Label("Password: ", [Link]); }

// Create TextFields
// Draw output on Applet
name = new TextField(15);
public void paint(Graphics g) {
pass = new TextField(10);
[Link](msg, 20, 100);
[Link]('*'); // Hide password characters
}
TextArea
• A multiline text input component in AWT, used when a single-line
TextField is insufficient, ideal for forms, editors, or logs. Subclass of
TextComponent.
Constructor Description
Creates an empty TextArea with default size and scrollbars
TextArea()
(SCROLLBARS_BOTH).

Creates an empty TextArea with specified height (numLines) and


TextArea(int numLines, int numChars)
width (numChars) in characters (approximate, depends on font).

TextArea(String str) Creates a TextArea with initial text str and default size/scrollbars.

Creates a TextArea with initial text str, specified height


TextArea(String str, int numLines, int numChars)
(numLines), and width (numChars).

Creates a TextArea with initial text str, specified size, and


scrollbar settings (sBars): SCROLLBARS_BOTH,
TextArea(String str, int numLines, int numChars, int sBars)
SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE, or
SCROLLBARS_VERTICAL_ONLY.
Methods (Inherited from TextComponent)
String getText() Returns the current text as a String.
void setText(String str) Sets the text to str, replacing existing content.
String getSelectedText() Returns the currently selected (highlighted) text.
void select(int start, int end) Selects text from start to end-1.
boolean isEditable() Returns true if editable, false if read-only.
Sets whether the TextArea is editable (true) or
void setEditable(boolean editable)
read-only (false).
Methods (Specific to TextArea)
void append(String str) Appends str to the end of the current text.
void insert(String str, int index) Inserts str at the specified index.
void replaceRange(String str, int startIndex, int Replaces text from startIndex to endIndex-1 with
endIndex) str.
import [Link].*;
import [Link].*;
/*
<applet code=“TextAreaDemo" width=250 height=150>
</applet>
*/

public class TextAreaDemo extends Applet {


public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
Lists
• A compact, multiple-choice, scrolling selection list in AWT, showing
multiple visible choices unlike the single-item Choice object. Supports
single or multiple selections.

Constructor Description

Creates a List control that allows only one item to be


List() selected, with default visible rows.
Creates a List with numRows entries always visible
List(int numRows) (others scrollable), allowing only one item to be
selected.

Creates a List with numRows visible entries; if


List(int numRows, boolean multipleSelect) multipleSelect is true, multiple items can be selected,
otherwise only one item can be selected.
Methods (Adding Items)
void add(String name) Adds name to the end of the list.

void add(String name, int index) Adds name at the specified index (0-based); use -1 to add to the end.

Methods (Single Selection)


Returns the name of the selected item as a String; returns null if no selection
String getSelectedItem()
or multiple items selected.
Returns the index of the selected item (0-based); returns -1 if no selection or
int getSelectedIndex()
multiple items selected.
Methods (Multiple Selection)
String[] getSelectedItems() Returns an array of names of currently selected items.

int[] getSelectedIndexes() Returns an array of indexes of currently selected items.

Other Methods
int getItemCount() Returns the total number of items in the list.

void select(int index) Sets the item at the specified index (0-based) as the selected item.

String getItem(int index) Returns the name of the item at the specified index.
Event Types:
• Double-click (ActionEvent): Triggered when a list item is double-clicked. The
getActionCommand() method of the ActionEvent object returns the name of the
selected item.
• Single-click (ItemEvent): Triggered when an item is selected or deselected. The
getStateChange() method indicates if it’s a SELECTED or DESELECTED event, and
getItemSelectable() returns the List object that triggered the event.
Interfaces:
• Implement ActionListener for double-click events.
• Implement ItemListener for single-click selection/deselection events.
// Demonstrate Lists. // add lists to window
import [Link].*; add(os);
import [Link].*; add(browser);
import [Link].*; // register to receive action events
/* [Link](this);
<applet code="ListDemo" width=300 height=180> [Link](this);
</applet> }
*/ public void actionPerformed(ActionEvent ae) {
public class ListDemo extends Applet implements ActionListener { repaint();
List os, browser; }
String msg = ""; // Display current selections.
public void init() { public void paint(Graphics g) {
os = new List(4, true); int idx[];
browser = new List(4, false); msg = "Current OS: ";
// add items to os list idx = [Link]();
[Link]("Windows XP"); for(int i=0; i<[Link]; i++)
[Link]("Windows Vista"); msg += [Link](idx[i]) + " ";
[Link]("Solaris"); [Link](msg, 6, 120);
[Link]("Mac OS"); msg = "Current Browser: ";
// add items to browser list msg += [Link]();
[Link]("Internet Explorer"); [Link](msg, 6, 140);
[Link]("Firefox"); }
[Link]("Opera"); }
[Link](1);
Choice
• The Choice class in Java’s AWT creates a dropdown menu (pop-up list)
where users can select one item from a list of options. It’s a compact
menu that shows only the selected item when inactive and expands to
display all options when clicked. Below is a complete summary of the
text’s content:
• Purpose and Appearance:
• Used to create a pop-up list for user selection, functioning as a type of menu.
• When inactive, it displays only the currently selected item to save space.
• When clicked, the full list of choices appears, allowing the user to pick a new
item.
• Each item in the list is a string, shown as a left-justified label in the order added.
Constructors for [Link] Class
• Choice() Creates a new, empty Choice menu (pop-up list). This is the default constructor,
initializing an empty dropdown with no items. By default, the first added item will be
selected.
Methods for [Link] Class (Key Methods from Text)
• void add(String name) Adds a string item to the end of the Choice list. Items are appended
in the order of calls to this method, appearing as left-justified labels.
• String getSelectedItem() Returns the name of the currently selected item in the Choice
menu as a string.
• int getSelectedIndex() Returns the zero-based index of the currently selected item (0 for
the first item).
• int getItemCount() Returns the total number of items in the Choice list.
• void select(int index) Sets the selected item to the one at the specified zero-based index.
• void select(String name) Sets the selected item to the one matching the specified string
name in the list.
• String getItem(int index) Returns the name of the item at the specified zero-based index
in the list.
import [Link].*;
import [Link].*; // Add Choice menus to applet
import [Link].*; add(color);
add(shape);
/*
<applet code="SimpleChoiceDemo" width=250 height=150> // Register ItemListener for both menus
</applet> [Link](this);
*/ [Link](this);
public class SimpleChoiceDemo extends Applet implements ItemListener { }
Choice color, shape; // Two Choice menus
String msg = ""; // Message to display selections // Handle item selection events
public void init() { public void itemStateChanged(ItemEvent ie) {
// Create Choice menus repaint(); // Redraw applet when selection changes
color = new Choice(); }
shape = new Choice(); // Display current selections
public void paint(Graphics g) {
// Add items to color list msg = "Color: " + [Link]();
[Link]("Red"); [Link](msg, 10, 100);
[Link]("Blue"); msg = "Shape: " + [Link]();
[Link](msg, 10, 120);
// Add items to shape list }
[Link]("Circle"); }
[Link]("Square");
Sliders in Java GUI
• Sliders allow users to select a value from a defined range by dragging a knob or
thumb along a track. They are ideal for inputting numerical values within a
specific range, such as adjusting settings like volume, brightness, or progress.
• Purpose of Sliders
• Enable intuitive selection of a value from a continuous or discrete range (e.g., 0 to 100).
• Provide visual feedback as the user moves the knob.
• Support fine-tuned control for settings or parameters.
• Typical Use Cases
• Adjusting settings (e.g., volume, font size, color intensity).
• Selecting a value within a range (e.g., age, temperature).
• Controlling progress or position (e.g., in media players or scrollable content)
Menus in Java GUI
• Menus provide a structured way to organize and access commands or options
in a GUI application. They are typically displayed as dropdowns at the top of a
window (menu bar) or as context menus (right-click menus).
• Purpose of Menus
• Organize application commands (e.g., File, Edit, Help).
• Provide quick access to actions (e.g., Save, Copy, Exit).
• Support hierarchical navigation with submenus for grouped functionality.
• Typical Use Cases
• Application navigation (e.g., File > New, Open, Save).
• Context-sensitive actions (e.g., right-click to copy/paste).
• Organizing settings or tools in complex applications.
Dialog Boxes in Java
• A Dialog Box is a special type of window used to display messages or to
obtain user input.
• They are usually child windows of a top-level window (like a Frame).
• Dialog boxes don’t have menu bars, but they can contain other GUI
controls (labels, buttons, text fields, etc.).
• Types of Dialog Boxes
• Modal Dialog Box
• Blocks user interaction with other windows until it is closed.
• Example: Save File dialog.
• Modeless Dialog Box
• Does not block other windows; user can still interact with the rest of the program.
• Example: Find/Replace dialog in text editors.
• In AWT, dialog boxes are implemented using the Dialog class.
• Two commonly used constructors:
• Dialog(Frame parentWindow, boolean mode)
• Dialog(Frame parentWindow, String title, boolean mode)
 parentWindow → the owner of the dialog box.
 mode → if true, dialog is modal; if false, it is modeless.
 title → optional string for dialog title.
import [Link]; [Link](new FlowLayout());

import [Link].*; [Link](new Label("Hello! This is a Dialog Box"));

import [Link].*;

// Close button inside dialog

/* Button closeButton = new Button("Close");

<applet code="DialogDemo" width=300 height=200> [Link](closeButton);

</applet>

*/ // Button actions using anonymous inner classes

[Link](new ActionListener() {

public class DialogDemo extends Applet { public void actionPerformed(ActionEvent e) {

Button openButton; [Link](true);

Dialog dialog; }

});

public void init() {

// Create main frame [Link](new ActionListener() {

Frame f = new Frame("Dialog Demo"); public void actionPerformed(ActionEvent e) {

[Link](300, 200); [Link](false);

[Link](new FlowLayout()); }

});

// Create button to open dialog

openButton = new Button("Open Dialog"); // Show the main frame

[Link](openButton); [Link](true);

// Create dialog box (modal) }

dialog = new Dialog(f, "My Dialog", true);

[Link](200, 100);
Exception
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling Fundamentals :
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that you want to monitor for exceptions are contained within a try block. If
an exception occurs within the try block, it is thrown.
Your code can catch this exception using catch and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Java Exception Keywords:
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
The "try" keyword is used to specify a block where we should
try place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.
The "catch" block is used to handle the exception. It must be
catch preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
The "finally" block is used to execute the necessary code of the
finally
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It specifies
throws that there may occur an exception in the method. It doesn't
throw an exception. It is always used with method signature.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions :
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions [Link], SQLException etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Uncaught Exceptions in Java :
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions.
Example:
import [Link];
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner([Link]);
[Link]("Enter the a and b values: ");
int a = [Link]();
int b = [Link]();
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
}
In the above example code, we are not used try and catch blocks, but when the value of b is
zero the division by zero exception occurs and it caught by the default exception handler.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not.
If exception is not handled, JVM provides a default exception handler that performs the
following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed
Using try and catch:
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
When an exception is thrown, it is caught by the corresponding catch statement which then
processes the exception.
When no exception is thrown, try block ends normally and catch statements are bypassed.
Thus catch statements are executed only if an exception is thrown.
Types of Exceptions:
Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.

Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
List of common checked exceptions in Java:
Exception class Description

IOException This exception is raised when an input/output operation fails

SQLException This exception is raised when a database operation fails

ClassNotFoundException This exception is raised when a class cannot be found.

This exception is raised when an object cannot be


InstantiationException
instantiated.

NoSuchMethodException This exception is raised when a method cannot be found.


List of common unchecked exceptions in Java:
Exception classes Description
RuntimeException This is the superclass of all unchecked exceptions.

NullPointerException: This exception is raised when a null value is used where


an object is required.

ArithmeticException This exception is raised when an arithmetic operation


fails.

ArrayIndexOutOfBoundsException This exception is raised when an array index is out of


bounds.

IllegalArgumentException This exception is raised when an illegal argument is used.

IllegalStateException This exception is raised when an illegal state is detected.

ConcurrentModificationException This exception is raised when a collection is modified


while it is being iterated over.
Errors in Java:
Error classes Description

OutOfMemoryError This error is raised when the JVM runs out of memory.

StackOverflowError This error is raised when a stack overflow occurs.

VirtualMachineError This is the superclass of all errors that occur in the JVM.

AssertionError This error is raised when an assertion fails.


NoClassDefFoundError This error is raised when a class cannot be found.
LinkageError This error is raised when a linkage problem occurs.

This error is raised when an exception occurs in the static


ExceptionInInitializerError:
initializer of a class.
The Consequences of an Uncaught Exception
public class TryCatchExample1
{
public static void main(String[] args) {
int data=50/0; //may throw exception
[Link]("rest of the code");
}
}
Output:
Exception in thread "main" [Link]: / by zero
in the example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There might be any number lines of code after the exception. If the exception is not handled,
all the code below the exception won't be executed.
Using try and catch:
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
The try and catch keywords come in pairs:

Syntax:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e)
{ // catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
output:
Division by zero.
After catch statement.
Notice that the call to println( ) inside the try block is never executed. Once an exception is
thrown, program control transfers out of the try block into the catch block.
Put differently, catch is not “called,” so execution never “returns” to the try block from a
catch. Thus, the line “This will not be printed.” is not displayed.
Once the catch statement has executed, program control continues with the next line in the
program following the entire try/catch mechanism.
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}

}
Output:
[Link]: / by zero
rest of the code
public class TryCatchExample5
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}
}
Output:
Can't divided by zero
Solution by exception handling
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
Ourput:
[Link]: / by zero
rest of the code
Multiple Catch Blocks in Java
Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown
from a particular code section. A try block can have multiple catch blocks to handle multiple
exceptions.

Syntax: Multiple Catch Blocks

try {
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown to
the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Handling Multiple Exceptions Within A Single Catch Block:
public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
int b = 0;
int c = 1/b;
[Link]("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
[Link]("Exception thrown :" + e);
}
[Link]("Out of the block");
}
}
Output
Exception thrown :[Link]: / by zero
Out of the block
Java Nested try block :
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).
Why use nested try block : }
Syntax: .... } catch(Exception e1)
//main try block {
try { //exception message
statement 1; }
statement 2; }
//try catch block within another try block //catch block of parent (outer) try block
try { catch(Exception e3)
statement 3; {
statement 4; //exception message
//try catch block within nested try block }
try {
statement 5;
statement 6;
} catch(Exception e2)
{
//exception message
public class NestedTryBlock a[5]=4;
{ }
public static void main(String args[]){ //catch block of inner try block 2
//outer try block catch(ArrayIndexOutOfBoundsException e)
try{ {
//inner try block 1 [Link](e);
try{ }
[Link]("going to divide by 0"); [Link]("other statement");
int b =39/0; } }
//catch block of inner try block 1 //catch block of outer try block
catch(ArithmeticException e) catch(Exception e)
{ {
[Link](e); [Link]("handled the exception (outer catch)");
} }
//inner try block 2 [Link]("normal flow..");
try{ }
int a[]=new int[5]; }
//assigning the value out of array bounds
Output:

When any try block does not have a catch block for a particular exception, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch block
of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for
that exception.
Java throw, throws and finally Keyword:
Throw, throws and finally are the keywords in Java that are used in exception handling.

The throw keyword is used to throw an exception

Throws is used to declare the list of possible exceptions with the method signature.

Whereas finally block is used to execute essential code, specially to release the occupied
resources.
Java Throw
The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can
be thrown. Program execution stops on encountering throw statement, and the closest catch statement is
checked for matching type of exception.
Syntax :
throw new ExceptionType("Error message");

if (balance < withdrawAmount) {


throw new InsufficientBalanceException("You have insufficient balance");
}
In the above code, if the balance is less than the withdraw amount, an InsufficientBalanceException is thrown
using the Throw keyword. A “try-catch” block will catch the exception in the calling code. Once this is done, an
exception message, “You have insufficient balance,” will be displayed.
public class ThrowExample {
public static void main(String[] args) {
try {
// Call a method that throws an exception
checkAge(15);
} catch (Exception e) {
[Link]("Caught an exception: " +
[Link]());
}
}
// Method that throws an exception if age is less than 18
public static void checkAge(int age) throws Exception
{
if (age < 18) {
throw new Exception("Age must be 18 or older.");
} else {
[Link]("Age is valid: " + age);
}
}
}
Java throws Keyword
The throws keyword is used to declare the list of exception that a method may throw during
execution of program.
Any method that is capable of causing exceptions must list all the exceptions possible during
its execution, so that anyone calling that method gets a prior knowledge about which
exceptions are to be handled.
A method can do so by using the throws keyword.
Syntax:
type method_name(parameter_list) throws exception_list
{
// definition of method
}
Example throws Keyword
the throws keyword in Java is used in method signatures to declare that a method can throw one or more
exceptions. This provides information to the caller of the method about what exceptions might be thrown,
allowing the caller to handle them appropriately.
class Test
{
static void check() throws ArithmeticException
{
[Link]("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
[Link]("caught" + e);
}
}
}
output:
Inside check function
[Link]: demo
• Difference between throw and throws
throw throws

throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.

throw keyword is followed by an instance of throws keyword is followed by one or more Exception
Throwable class or one of its sub-classes. class names separated by commas.

throws keyword is used with method signature


throw keyword is declared inside a method body.
(method declaration).

We cannot throw multiple exceptions using throw We can declare multiple exceptions (separated by
keyword. commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is always
executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what happens in the protected code. A finally block appears at
the end of catch block.
Example finally Block
In this example, we are using finally block along with try block. This program throws an exception and due to
exception, program terminates its execution but see code written inside the finally block executed. It is because
of nature of finally block that guarantees to execute the code.
public class FinallyExample {
public static void main(String args[]){
try {
[Link]("Inside try block");
// below code throws divide by zero exception
int data=25/0;
[Link](data);
}
// handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}
// executes regardless of exception occurred or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
// Java program to demonstrate working of try,
// catch and finally

class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
[Link]("result" + result);
}

catch (ArithmeticException e) {
[Link]("Exception caught:Division by zero");
}

finally {
Output
Exception caught:Division by zero
I am in final block
Why is finally block needed?
In Java, the finally block is used to place critical code such as cleanup code, closing a file, or closing a connection.
The finally block checks whether an exception has been raised and whether it has been handled. Regardless of
whether the exception happens, a fina block contains all the crucial statements.
class MyException extends Exception {
{ [Link](a+b);
private int ex; }
MyException(int a) }
{
ex = a; public static void main(String[] args)
} {
public String toString() try
{ {
return "MyException[" + ex +"] is less than zero"; sum(-10, 10);
} }
} catch(MyException me)
{
class test [Link](me); //it calls the toString() method
{ of user-defined Exception
static void sum(int a,int b) throws MyException }
{ }
if(a<0) }
{
throw new MyException(a); //calling constructor of
user-defined exception class
}
else
Output
MyException[-10] is less than zero

This example defines a subclass of Exception called MyException. This subclass is quite
simple: it has only a constructor plus an overloaded toString( ) method that displays the
value of the exception. The ExceptionDemo class defines a method named compute( ) that
throws a MyException object. The exception is thrown when compute( )’s integer parameter
is greater than 10. The main( ) method sets up an exception handler for MyException, then
calls compute( ) with a legal value (less than 10) and an illegal one to show both paths
through
the code. Here is the result:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Java Custom Exception
The custom exception refers to the creation of your own exception to customize
an exception according to the needs. The custom exceptions are derived from
the Exception class.
Create a Custom Exception in Java:
Creating your own exception subclass in Java allows you to define custom exceptions that
serve to specific errors in your application. This approach helps in improving code readability
and managing exceptional conditions effectively.

Syntax:
class MyException extends Exception {
}
class InvalidAgeException extends Exception }
{ }
public InvalidAgeException(String message) public static void main(String[] args) {
{ UserRegistration registration = new UserRegistration();
super(message); try {
} [Link](“XYZ", 20); // Valid registration
} [Link](“ABC", 16); // Invalid age, will
throw exception
public class UserRegistration } catch (InvalidAgeException e)
{ {
public void registerUser(String name, int age) throws [Link]("Registration Error: " +
InvalidAgeException { [Link]());
if (age < 18) }
{ }
throw new InvalidAgeException("User " + name + " must }
be 18 years or older.");
}
else
{
[Link]("User " + name + " registered
successfully.");
InvalidAgeException extends the Exception class, making it a checked exception (since it
extends Exception).
InvalidAgeException(String message) is the constructor that initializes the exception message
using super(message)
class UserRegistration where we will validate the age of a user during registration and throw
InvalidAgeException if the age is less than 18.
InvalidAgeException Class Extends Exception, making it a checked [Link] Provides a
constructor that calls super(message) to initialize the exception message.
In UserRegistration Class registerUser(String name, int age): Validates the age provided during
user registration. If age < 18, it throws InvalidAgeException with a specific error message. In
main() method, demonstrates the usage of registerUser() method with both valid and invalid
age inputs, catching InvalidAgeException to handle the error scenario.
The advantages of Exception Handling in Java are as follows:
Provision to Complete Program Execution
Easy Identification of Program Code and Error-Handling Code
Propagation of Errors
Meaningful Error Reporting
Identifying Error Types
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with
it that provides the error description. These exceptions may be related to user inputs, server,
etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
The syntax of the Java throw keyword is given below.
throw new exception_class("error message");
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}
Output:
Java Catch Multiple Exceptions Java
Multi-catch block A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
} catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
} catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
public class MultipleCatchBlock2 [Link]("Parent Exception occurs");
{ }
public static void main(String[] args) [Link]("rest of the code");
{ }
try }
{
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{

[Link]("ArrayIndexOutOfBounds Exception
occurs");
}
catch(Exception e)
{

You might also like