UNIT 4
1. What is thread? What is difference between multiprocessing
and multithreading?
A Thread is the smallest unit of processing that can be executed
independently. It is a lightweight process that runs within a program.
Threads share the same memory space, code, and data of the application
they belong to, which makes context switching between them very fast.
Multiprocessing vs. Multithreading
Feature Multiprocessing Multithreading
Execution of multiple
Execution of multiple
Concept threads within a single
processes concurrently.
process concurrently.
Less sharing; each High sharing; all
Resource process has its own threads within a process
Sharing separate memory space share the same memory
(address space). space and resources.
Heavyweight; requires Lightweight; only
Context the OS to save and load requires saving and
Switching memory maps, registers, loading register state
etc. (Slower). (Faster).
Complex and slower (via Simple and faster
Communicati
IPC mechanisms like (directly accessing
on
pipes, message queues). shared memory).
High (involves
Creation Low (only requires small
copying/setting up entire
Overhead stack allocation).
process environment).
2. Describe the complete life cycle of threads. (Or) Explain the
various states of Thread?
A thread goes through several distinct phases, or states, from its creation
until its completion. The [Link] enum defines the official
states.
Thread Life Cycle
1. New:
o Description: The thread is created (new Thread()) but has
not yet started execution. It is not yet alive.
o Transition: Moves to Runnable when the start() method is
called.
2. Runnable:
o Description: The thread is ready to run and is waiting for CPU
time. It might be currently running, or it might be waiting in a
queue of runnable threads.
o Transition: The thread scheduler selects it to run (Running).
It can move to Waiting, Timed Waiting, or Blocked based
on external events.
3. Running:
o Description: The thread is actively executing its code on the
CPU.
o Transition: Can move to Runnable (if its time slice ends—
preemption), Blocked (waiting for a lock), Waiting (calling
wait()), Timed Waiting (calling sleep()), or Terminated (if
run() completes).
4. Blocked (Waiting for Monitor Lock):
o Description: The thread is waiting for a monitor lock to
enter or re-enter a synchronized block or method.
o Transition: Moves back to Runnable when the lock becomes
available and the thread reacquires it.
5. Waiting:
o Description: The thread is indefinitely waiting for another
thread to perform a particular action (e.g., calling notify() or
notifyAll()).
o Transitions: Moves to Runnable when another thread calls
notify() or notifyAll(). Methods causing this state include
[Link](), [Link]() (without timeout), and
[Link]().
6. Timed Waiting:
o Description: The thread is waiting for another thread to
perform an action, but with a specified maximum waiting
time.
o Transitions: Moves to Runnable when the timeout expires or
when the required action occurs. Methods causing this state
include [Link](ms), [Link](ms), and
[Link](ms).
7. Terminated (Dead):
o Description: The thread has completed its execution (its
run() method has finished) or has been abnormally terminated
(e.g., due to an uncaught exception).
o Note: A terminated thread cannot be restarted.
3. What is thread? Explain various ways to create a thread.
Thread is defined in Question 1.
Java provides two primary ways to create a new thread of execution:
1. By Extending the [Link] Class
1. Create a class that extends Thread.
2. Override the run() method with the code you want the thread to
execute.
3. Create an instance of the class.
4. Call the start() method on the instance, which in turn calls the run()
method.
Example:
Java
class MyThread extends Thread {
@Override
public void run() {
[Link]("Thread created by extending Thread.");
}
// Usage: new MyThread().start();
2. By Implementing the [Link] Interface
1. Create a class that implements the Runnable interface.
2. Implement the run() method.
3. Create an object of this Runnable class.
4. Pass the Runnable object to the constructor of the Thread class.
5. Call the start() method on the Thread object.
Example:
Java
class MyRunnable implements Runnable {
@Override
public void run() {
[Link]("Thread created by implementing Runnable.");
// Usage: new Thread(new MyRunnable()).start();
Which way to choose?
Implementing Runnable is generally preferred because Java
does not support multiple inheritance of classes. Implementing
Runnable allows your class to still extend another class if needed.
4. Explain thread priorities and method to get a set priority
values.
Thread Priorities
Thread Priority is an integer value assigned to a thread that helps the
thread scheduler determine the order in which threads should be given
access to the CPU. Higher-priority threads are given preference over
lower-priority threads.
Priorities range from $\mathbf{1}$ (minimum) to $\mathbf{10}$
(maximum).
Default Priority: $\mathbf{5}$ (normal).
Java defines three standard constants in the Thread class:
Valu
Constant Description
e
Thread.MIN_PRIORI Minimum priority
1
TY value.
Thread.NORM_PRIO Default priority
5
RITY value.
Thread.MAX_PRIORI Maximum priority
10
TY value.
Important Note: Thread priority is heavily dependent on the underlying
Operating System's scheduling capabilities and may not guarantee
execution order. It is merely a hint to the scheduler.
Methods to Get and Set Priority Values
The [Link] class provides the following public methods:
1. public final int getPriority():
o Purpose: Returns the current priority level of the thread.
2. public final void setPriority(int newPriority):
o Purpose: Changes the priority of the thread to the value
specified by newPriority.
o Restriction: Throws an IllegalArgumentException if the value
is not between MIN_PRIORITY and MAX_PRIORITY.
Example:
Java
Thread t1 = new Thread(() -> [Link]("Low priority thread
running"));
Thread t2 = new Thread(() -> [Link]("High priority thread
running"));
// Set priorities
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.MAX_PRIORITY); // 10
// Get and print priorities
[Link]("t1 priority: " + [Link]());
[Link]("t2 priority: " + [Link]());
[Link]();
[Link]();
6. What is synchronization? How do we achieve it? Explain with
suitable example.
What is Synchronization?
Synchronization is the capability to control the access of multiple
threads to any shared resource, particularly shared data or code blocks. In
a multithreaded environment, if multiple threads try to modify the same
data concurrently, it can lead to data inconsistency and race
conditions. Synchronization ensures that only one thread can execute a
synchronized part of the code (the critical section) at a time, preventing
data corruption.
Java's synchronization is built around the concept of a monitor lock
(intrinsic lock). Every object in Java has an associated monitor lock.
How is Synchronization Achieved?
Synchronization is achieved in Java using the synchronized keyword:
1. Synchronized Method:
o The synchronized keyword is added to the method signature.
o When a thread enters a synchronized instance method, it
acquires the monitor lock of the object (this).
o If another thread tries to enter any synchronized method on
the same object, it is blocked until the first thread releases the
lock (by exiting the method).
Example: public synchronized void updateBalance(int amount) { ... }
2. Synchronized Block:
o The synchronized keyword is applied to a block of code,
specifying the object whose monitor lock is to be acquired.
This allows for finer-grained control over the critical section,
locking only the necessary code.
o Syntax: synchronized (lockObject) { // critical section }
Example: synchronized (this) { balance += amount; }
Example
Java
class Counter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++; // Critical section: shared resource modification
public int getCount() {
return count;
class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// Create two threads that call increment() 1000 times each
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) [Link]();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) [Link]();
});
[Link]();
[Link]();
[Link](); // Wait for t1 to finish
[Link](); // Wait for t2 to finish
// With synchronization, the final count is correctly 2000.
// Without synchronization, it would likely be less than 2000.
[Link]("Final Count: " + [Link]());
11. Write a brief note on Reading console Input and Writing
Console Output with examples.
Java handles console I/O using the standard input, output, and error
streams, managed by the static fields of the [Link] class.
Writing Console Output
Output is typically written using [Link], which is a PrintStream object.
Method Description Example
Prints data to the console
print() without adding a new line [Link]("Hello ");
character.
println() Prints data to the console [Link]("World!"
followed by a new line );
Method Description Example
character.
Provides formatted output
[Link]("Value is
printf() using format specifiers
%d", 10);
(similar to C's printf).
Used for writing error
System.e messages (usually appears [Link]("An error
rr in red or a separate occurred.");
stream).
Reading Console Input
Reading user input from the console is commonly done using the
[Link] class, introduced in Java 5. The Scanner object reads
from the standard input stream ([Link]).
Example:
Java
import [Link];
public class ConsoleInputDemo {
public static void main(String[] args) {
// Create a Scanner object to read from [Link]
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
// Read a line of text
String name = [Link]();
[Link]("Enter your age: ");
// Read an integer value
int age = [Link]();
[Link]("Hello, " + name + "! You are " + age + " years
old.");
// Always close the scanner to release resources
[Link]();
Other methods in Scanner include next(), nextByte(), nextDouble(), etc.
12. Explain the Java File class with examples.
The [Link] class is a fundamental class in Java I/O that represents a
file or directory path name in the file system. It is not used for reading or
writing data to a file, but rather for performing operations on the file
system itself (creation, deletion, renaming, listing contents, etc.).
Key Features and Methods
Method Description Example
new File(String Constructor to create a File File f = new
pathname) object for a given path. File("[Link]");
Creates a new empty file if
createNewFile() it does not already exist. [Link]();
Returns true on success.
Creates the directory
mkdir() [Link]();
specified by the path name.
Checks if the file or
exists() [Link]()
directory exists on the disk.
Checks if the object is a
isDirectory() [Link]()
directory.
Method Description Example
Returns the name of the file
getName() [Link]()
or directory.
getAbsolutePat Returns the absolute path of [Link](
h() the file or directory. )
Deletes the file or directory
delete() (must be empty). Returns [Link]()
true on success.
Returns an array of File
objects representing the
listFiles() [Link]()
files and directories inside
the current directory.
Example:
Java
import [Link];
import [Link];
public class FileDemo {
public static void main(String[] args) {
File file = new File("[Link]");
try {
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
if ([Link]()) {
[Link]("Path: " + [Link]());
}
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
13. Write a short note on Reading a File in Java.
Reading a file in Java involves opening an input stream from the file and
then reading the contents, typically character by character, line by line, or
byte by byte. The choice of class depends on the type of data being read
(text or binary) and the required efficiency.
1. Reading Character Data (Text Files)
The primary classes for reading text are:
FileReader: Used to read character streams from files. Suitable for
reading small text files.
BufferedReader: Often wraps a FileReader or other Reader. It reads
text from a character-input stream, buffering characters to provide
for the efficient reading of characters, arrays, and lines. The
readLine() method is most commonly used for line-by-line reading.
Example (Using BufferedReader for efficiency):
Java
import [Link];
import [Link];
import [Link];
public class ReadFileDemo {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
2. Reading Byte Data (Binary Files)
FileInputStream: Used to read a stream of raw bytes from a file.
Necessary for reading binary files like images or compiled .class
files.
14. Explain about Write To File in Java.
Writing to a file in Java involves opening an output stream to the file and
then writing the data (characters or bytes) to that stream. The process
must always ensure the stream is closed after writing to flush any
buffered data and release the file handle.
1. Writing Character Data (Text Files)
The primary classes for writing text are:
FileWriter: Used to write character streams to files. It can be set to
append to the file (by passing true to the constructor) or overwrite
it (default).
BufferedWriter: Often wraps a FileWriter. It buffers output to
increase efficiency and provides the newLine() method for writing
platform-specific line separators.
PrintWriter: Provides convenient methods like print(), println(), and
printf() for text output, often used for simplicity.
Example (Using FileWriter):
Java
import [Link];
import [Link];
public class WriteFileDemo {
public static void main(String[] args) {
String data = "Hello, Java I/O!\n";
// true means append data to the file, false/default means overwrite
try (FileWriter fw = new FileWriter("[Link]", true)) {
[Link](data);
[Link]("Data written to file.");
} catch (IOException e) {
[Link]("Error writing to file: " + [Link]());
2. Writing Byte Data (Binary Files)
FileOutputStream: Used to write a stream of raw bytes to a file.
Necessary for creating or modifying binary files.
15. Explain Console class in Java with an example.
The [Link] class is a utility class introduced in Java 6, primarily
used for console-based applications that interact with the user via a
terminal. It is suitable for reading textual input, especially passwords or
other sensitive data, as it provides methods to read input without echoing
the characters to the console.
Key Features
Password Reading: The readPassword() method reads a password
or sensitive information and returns it as a char[] array (which is
preferred over String for security, as it can be zeroed out
immediately after use).
Convenience: Provides simple methods like readLine(), format(),
and writer().
Availability: The Console object may not be available in all
execution environments (e.g., inside an IDE or background service).
You must check if [Link]() returns a non-null value before
using it.
Example:
Java
import [Link];
public class ConsoleDemo {
public static void main(String[] args) {
Console console = [Link]();
if (console != null) {
// Read username (echoed)
String username = [Link]("Enter username: ");
// Read password (not echoed)
char[] password = [Link]("Enter password: ");
[Link]("Welcome, %s!\n", username);
// For security, clear the password array after use
[Link](password, ' ');
} else {
[Link]("Console is not available. Try running from a
terminal.");
16. Write about Serialization in Java.
Serialization is the process of converting an object's state (its data and
fields) into a byte stream, which can then be saved to a file, database, or
transmitted across a network.
Deserialization is the reverse process: reconstructing the object from
the byte stream.
Key Aspects
1. Interface: For a class to be serializable, it must implement the
marker interface [Link]. This interface has no
methods but tags the class as capable of being serialized.
2. Transience: Fields that should not be saved (e.g., security data,
calculated fields) must be marked with the transient keyword.
Transient fields are set to their default values during deserialization.
3. Classes:
o ObjectOutputStream: Used to serialize an object (write the
object to a stream).
o ObjectInputStream: Used to deserialize an object (read the
object from a stream).
Example:
Java
import [Link].*;
// 1. Implement Serializable
class User implements Serializable {
String name;
// 2. Use transient for fields not to be serialized
transient String password;
public User(String n, String p) { [Link] = n; [Link] = p; }
public class SerializationDemo {
public static void main(String[] args) throws Exception {
User original = new User("Alice", "secret123");
// --- Serialization (Writing object to file) ---
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
[Link](original);
[Link]("User object serialized.");
// --- Deserialization (Reading object from file) ---
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) {
User restored = (User) [Link]();
// password will be null/default value because it was transient
[Link]("Restored User: " + [Link] + ",
Password: " + [Link]);
}
UNIT 5
1. What is Swing. Write the features of Swing.
What is Swing?
Swing is a set of classes in the Java Foundation Classes (JFC) that
provides a comprehensive and mature toolkit for building Graphical User
Interfaces (GUIs) in Java. Swing components are an extension of the
older Abstract Window Toolkit (AWT).
Swing components are lightweight (written purely in Java and draw their
own output, independent of the underlying OS window system).
Features of Swing
1. Platform Independent (Pure Java): Swing components are
"lightweight," meaning they do not rely on the native operating
system's widget set. They render their own look and feel, making
them look the same across all platforms.
2. Pluggable Look and Feel (PLAF): Allows the appearance of the
GUI to be changed dynamically at runtime. You can make a Swing
application look like it is running on Windows, macOS, or use a
custom look (like Metal, Nimbus).
3. Rich Set of Components: Provides more sophisticated
components than AWT, including tables (JTable), trees (JTree),
tabbed panes (JTabbedPane), scroll panes (JScrollPane), and
toolbars.
4. Extensible and Customizable: Components can be easily
extended and customized since they are not tied to native peer
classes.
5. MVC Architecture (Model-View-Controller): Swing components
are often designed following a decoupled model, where the
component's data (Model) is separated from its presentation
(View) and control logic (Controller).
2. Write about MVC architecture.
The Model-View-Controller (MVC) architecture is a design pattern
used to separate the representation of information from the user's
interaction with it. It is commonly applied in GUI development, and Swing
components are often designed with this decoupling principle.
Components of MVC
1. Model (Data/State):
o Represents the application's core data, business logic, and
state.
o It is independent of the user interface.
o The Model notifies the View whenever its data changes.
o In Swing: Examples include TableModel for JTable, Document
for JTextComponent.
2. View (Presentation/UI):
o Renders the Model's data to the user.
o It is responsible for all visual output.
o It receives updates from the Model and displays them.
o In Swing: The visual component itself (JTable, JButton) acts as
the View.
3. Controller (Logic/Input Handler):
o Handles user input (events like button clicks, key presses).
o It updates the Model in response to user actions.
o It may select a View to display the Model's data.
o In Swing: Often implemented via Event Listeners (e.g.,
ActionListener) which receive events and modify the Model.
Benefit of MVC
The main benefit is separation of concerns. Changes to the data
(Model) can be made without altering the UI (View), and vice versa, which
increases modularity, reusability, and maintainability of the code.
4. Discuss about Containers in Swing.
In GUI programming, a Container is a component that can hold and
manage other components (including other containers). They are essential
for organizing and structuring the layout of a GUI application.
Swing containers are derived from the [Link] class. The
primary top-level and general-purpose containers in Swing are:
Top-Level Containers
These containers provide the basic window structure for a Swing
application. They are non-visual containers that interact with the
underlying operating system's windowing capabilities.
1. JFrame: Represents the main application window with a title bar,
borders, and window controls (minimize, maximize, close). It is the
most commonly used top-level container.
2. JDialog: Used to create secondary windows, typically for user alerts,
prompts, or temporary information display.
3. JApplet (or JInternalFrame): Used for applets embedded in a web
browser (now largely obsolete) or internal frames within a desktop
application.
General-Purpose Containers
These containers are placed inside top-level containers and are used to
arrange other components using layout managers.
1. JPanel: The most versatile and commonly used intermediate
container. It is a general-purpose, lightweight container used to
group and arrange components (e.g., grouping a set of radio
buttons).
2. JTabbedPane: A container that lets you insert multiple components
(or other panels) into one window, separated by tabs.
3. JScrollPane: A container that provides a scrollable view of a
component. If a component (like a JTable or a large JTextArea) is too
large to fit in its display area, JScrollPane adds scroll bars.
Example of use: A JFrame contains a JPanel, and the JPanel holds a
JButton and a JLabel.
5. Define Layout Manager. Explain various types of layout
manager classes.
Definition of Layout Manager
A Layout Manager is an object associated with a container (like JFrame
or JPanel) that automatically arranges the components within that
container. It is responsible for determining the size and position of
components, ensuring the GUI handles resizing and different screen
resolutions gracefully.
The arrangement logic is separated from the components themselves.
Various Types of Layout Manager Classes
Layout
Description Example Use
Manager
Arranges components in a
row, from left to right, in the Simple forms or
FlowLayout order they are added. When toolbars where order
the row is full, it wraps to the matters.
next line.
Divides the container into five
regions: North, South, East, Main application
West, and Center. Only one frames with menus
BorderLayo
component can be placed in (North), status bars
ut
each region. The Center (South), and main
component gets any leftover content (Center).
space. (Default for JFrame).
Arranges components in a
Calculators or
rectangular grid of cells (rows
spreadsheets where
$\times$ columns). Each cell
GridLayout components need to
is the same size, and
be uniformly sized
components are placed
and aligned.
sequentially.
Treats each component
Wizards or step-by-
(usually a JPanel) as a "card"
step forms where
CardLayout in a deck. Only one
switching between
component is visible at a
screens is needed.
time.
GridBagLay A flexible and complex layout Complex professional
out that arranges components in forms where precise
Layout
Description Example Use
Manager
a grid but allows components control over
to span multiple rows and component
columns and be placed in placement and
specific locations. resizing is necessary.
6. Write about the Delegation Event Model.
The Delegation Event Model is the standard way event handling is
implemented in Java AWT and Swing. The core principle is that event
processing is delegated from the source object to one or more listener
objects.
Key Components of the Model
1. Event Source:
o The component where the event originated (e.g., a JButton
that is clicked, a JTextField where text is typed).
o The Source object maintains a list of registered Listeners.
2. Event:
o An object that encapsulates the information about the event
that occurred (e.g., a mouse click, a key press, or a window
closing).
o Event objects are subclasses of [Link] (e.g.,
ActionEvent, MouseEvent).
3. Event Listener (Handler):
o An object that waits for and processes the event.
o A Listener must implement a specific Event Listener
Interface (e.g., ActionListener, MouseListener).
o The Listener registers with the Source component.
Working Mechanism
1. Registration: The Listener object is registered with the Source
object using a method like [Link](listener).
2. Event Generation: When an event occurs (e.g., user clicks the
button), the Source creates an appropriate Event object
(ActionEvent).
3. Delegation/Invocation: The Source object calls the appropriate
method on every registered Listener object, passing the Event
object as an argument.
4. Handling: The Listener's method executes the code (logic)
intended to respond to the event.
Example: A button (JButton - Source) needs to respond to a click. A class
implementing ActionListener (Listener) is created and registered with
the button using [Link](listener). When clicked, the
button calls the listener's actionPerformed(ActionEvent) method.
8. Discuss about Event Classes in Java.
Event Classes are objects that encapsulate information about an event
that occurred within the GUI (or other parts of the Java environment). All
event classes in the Delegation Event Model extend the base class
[Link].
Events are organized into categories, each with a corresponding class and
listener interface.
Common GUI Event Classes
Key Source
Event Class Package Description
Component
Generated when a
component-
specific action
JButton,
[Link] occurs (e.g.,
ActionEvent JMenuItem,
nt button click, menu
JTextField
item selection,
pressing Enter in a
text field).
MouseEvent [Link] Generated by user All
nt mouse interaction Component
(e.g., pressing, subclasses
releasing, moving,
Key Source
Event Class Package Description
Component
clicking a mouse
button).
Generated by
All
[Link] keyboard activity
KeyEvent Component
nt (pressing or
subclasses
releasing a key).
Generated when
JCheckBox,
[Link] an item is selected
ItemEvent JRadioButton,
nt or deselected
JComboBox
(change of state).
Generated by
actions on the
application window
[Link] JFrame,
WindowEvent (e.g., opening,
nt JDialog
closing,
minimizing,
maximizing).
Generated by
AdjustmentEv [Link] interacting with
JScrollBar
ent nt adjustable objects
(e.g., scroll bars).
Key Methods
All event classes have methods to:
getSource(): Returns the object that generated the event.
getID(): Returns the type of the event (e.g.,
ActionEvent.ACTION_PERFORMED).
9. Explain the Handling mouse and keyboard events with
examples.
Handling mouse and keyboard events involves implementing the
corresponding listener interfaces and registering them with the
appropriate component.
1. Handling Mouse Events
Mouse events are handled by two main interfaces:
MouseListener: Handles primary mouse actions (press, release,
click, enter, exit).
o Methods: mousePressed(), mouseReleased(), mouseClicked(),
mouseEntered(), mouseExited().
MouseMotionListener: Handles mouse movement and dragging.
o Methods: mouseMoved(), mouseDragged().
Example:
Java
import [Link];
import [Link];
import [Link];
class MousePanel extends JPanel {
public MousePanel() {
// Use MouseAdapter for convenience (only implement methods you
need)
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// [Link]() and [Link]() get the click coordinates
[Link]("Mouse clicked at: (" + [Link]() + ", " +
[Link]() + ")");
});
}
2. Handling Keyboard Events
Keyboard events are handled by the KeyListener interface. It is typically
registered on the component that has focus.
Methods:
o keyPressed(KeyEvent e): Invoked when a key is pressed
down.
o keyReleased(KeyEvent e): Invoked when a key is released.
o keyTyped(KeyEvent e): Invoked when a character is
generated by key press (not for every key like Shift, Ctrl).
Example:
Java
import [Link];
import [Link];
import [Link];
class KeyInput extends JTextField implements KeyListener {
public KeyInput() {
[Link](this);
@Override
public void keyPressed(KeyEvent e) {
// [Link]() returns the key code (e.g., KeyEvent.VK_ENTER)
if ([Link]() == KeyEvent.VK_ENTER) {
[Link]("Enter key pressed!");
// Other required methods must be implemented, even if empty
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
10. Explain about Adapter classes with examples.
Adapter Classes are abstract classes provided in the [Link]
package that provide default (empty) implementations for all the
methods in their corresponding Listener Interfaces.
Purpose and Benefit
Listener interfaces that have multiple methods (like MouseListener with
five methods or WindowListener with seven methods) require a class to
implement all of them, even if the programmer only needs to use one or
two.
Adapter classes solve this:
Instead of implementing the full interface, the user can extend the
corresponding Adapter class.
The user only needs to override the specific method(s) required
for their event handling logic.
Common Adapter Classes
Listener Corresponding
Useful For
Interface Adapter Class
Handling only a few
MouseListener MouseAdapter
mouse clicks/presses.
MouseMotionListen MouseMotionAda Handling only mouse
er pter movement or dragging.
Handling only a specific
WindowListener WindowAdapter window action (e.g.,
windowClosing()).
KeyListener (None) KeyListener has only
three methods
(keyPressed,
keyReleased, keyTyped),
so an Adapter class is not
Listener Corresponding
Useful For
Interface Adapter Class
typically provided or
necessary.
Example (Using WindowAdapter):
To make a JFrame close when the 'X' button is clicked, you only need the
windowClosing method, not the other six in WindowListener.
Java
import [Link];
import [Link];
import [Link];
class FrameAdapterDemo extends JFrame {
public FrameAdapterDemo() {
[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// Only this method is overridden; others remain empty
[Link]("Window is closing. Terminating
application.");
[Link](0);
});
// ... frame setup ...
12. Write a brief note on Anonymous inner Classes in Java.
An Anonymous Inner Class is a local class defined and instantiated in a
single expression, having no name. It is typically used when you need to
create an object of an interface or a class with slight modifications
(overriding one or two methods) and the object is needed only once.
Characteristics
1. No Name: It cannot be referred to later.
2. Definition and Instantiation: It is defined using the new keyword,
followed by the interface name or superclass name, and then the
class body ({...}).
3. One-time Use: Ideal for implementing event listeners (the primary
use case in Swing/AWT).
4. Local Scope: It can access the final (or effectively final) local
variables of the enclosing method.
Primary Use in Event Handling
Anonymous inner classes allow event handling code to be placed right
where the listener is registered, making the code concise and
readable.
Example (Handling Button Click):
Java
import [Link];
import [Link];
import [Link];
public class AnonymousDemo {
public static void main(String[] args) {
JButton button = new JButton("Click Me");
// Registering a listener using an Anonymous Inner Class
[Link](new ActionListener() {
// This class has no name and only exists to implement this one
method
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked using an anonymous
listener.");
});
// ... frame setup ...