Short Answer Type Questions
[Link] is meant by autoboxing and unboxing in Java? Give an example illustrating
both.
Autoboxing :It is the automatic conversion of a primitive type into its corresponding wrapper
class object.
Example:
int num = 10; // primitive int
Integer obj = num; // autoboxing: int → Integer
[Link](obj);
Unboxing :It is the automatic conversion of a wrapper class object back to its corresponding
primitive type.
Example:
Integer obj = 25; // wrapper object
int num = obj; // unboxing: Integer → int
[Link](num);
2. Define an event listener and mention any two commonly used listener interfaces in
Java.
• A listener is an object that is notified when an event occurs.
• Event has two major requirements.
1. It must have been registered with one or more sources to receive notifications about
specific types of events.
2. It must implement methods to receive and process these notifications.
Common Listener Interfaces:
1. ActionListener – for button or menu actions
2. MouseListener – for mouse-related events
3. Explain the purpose of a layout manager in GUI applications and give examples of
any two layout types.
A Layout Manager in Java is an object that controls the size, position, and arrangement
of components (like buttons, text fields, and labels) within a container such as a JFrame or
JPanel.
Purpose:
Automatically arrange components within a container.
Maintain consistent spacing, alignment, and positioning.
Adapt layout dynamically to container resizing or screen changes.
Simplify GUI design and improve usability.
[Link] any two life-cycle methods of an applet and briefly state their function.
• Applet is a public class which is predefined by [Link] .The life cycle
methods of an applet are:
• init( ): The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
• start( ): The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Whereas init( ) is called once—the first time an applet is
loaded—start( ) is called each time an applet's HTML document is displayed onscreen.
So, if a user leaves a web page and comes back, the applet resumes execution at start( ).
5. What are adapter classes in event handling? Why are they useful?
An adapter class in Java is an abstract class that provides empty implementations of
all methods in a listener interface.
It allows developers to override only the methods they need, instead of implementing
all methods from the listener interface.
Example:
import [Link].*;
public class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked!");
}
}
6. Mention two advantages of Swing over AWT with respect to component behavior
and portability.
7. List any two differences between applets and applications in Java.
8. Define daemon threads and state one of their uses.
A daemon thread is a background thread that runs continuously to provide services to
other [Link] automatically terminates when all non-daemon threads finish.
Use:
Used for background services like garbage collection, timer tasks, or auto-saving.
Example:
Thread t = new Thread(() -> [Link]("Daemon thread"));
[Link](true);
[Link]();
9. What is an enumeration in Java?
An Enumeration (enum) in Java is a special data type that defines a fixed set of named
constants.
Example:
enum Direction { NORTH, SOUTH, EAST, WEST }
Direction d = [Link];
[Link](d);
Use:
Improves code readability and safety by grouping related constants.
10. Mention two advantages of using Generics in Java.
Two advantages of using Generics in Java:
1. Type Safety:
Generics allow you to specify the type of objects that a collection or class can
hold, enabling the compiler to catch type mismatch errors at compile time
rather than at runtime.
This reduces runtime ClassCastException errors and makes the code more
reliable.
2. Elimination of Type Casting:
With generics, you don't need to explicitly cast objects when retrieving them
from collections.
This leads to cleaner, easier-to-read code and reduces the chance of casting
errors.
11. What is MVC architecture in SWING?
MVC (Model-View-Controller) architecture in Swing is a design pattern that separates a
GUI component into three interconnected components to improve modularity and
manageability:
1. Model: Encapsulates the data and business logic. It represents the application's
dynamic data structure, independent of the user interface.
2. View: Responsible for displaying the data (model) to the user. It handles the visual
representation of the model.
3. Controller: Acts as an intermediary between the model and the view. It processes
user input, updates the model, and may update the view accordingly.
Essay / Problem Solving Type Questions
[Link] between method overloading and method overriding with appropriate
examples. Write a Java program that demonstrates hierarchical inheritance.
Example: Method Overloading
class MathOperation {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class OverloadExample {
public static void main(String[] args) {
MathOperation m = new MathOperation();
[Link]([Link](5, 10)); // Calls int version
[Link]([Link](5.5, 2.5)); // Calls double version
}
}
Example: Method Overriding
class Animal {
void sound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class OverrideExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link](); // Calls Dog's version
}
}
2. Java Program Demonstrating Hierarchical Inheritance
Example:
// Base class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Derived class 1
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
// Derived class 2
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link](); // Output: Dog barks
[Link](); // Output: Cat meows
}
}
[Link] the thread life cycle in Java, highlighting the major states. Write a program
that creates two threads—one printing prime numbers and the other printing composite
numbers up to 20.
Thread Life Cycle in Java
A thread in Java goes through several states during its life cycle:
1. New: The thread is created but not yet started.
2. Runnable: The thread is ready to run and waiting for CPU time.
3. Running: The thread is executing.
4. Waiting: The thread is waiting indefinitely for another thread to perform a particular
action.
5. Timed Waiting: The thread is waiting for a specified amount of time.
6. Terminated (Dead): The thread has finished execution.
Program:
class PrimeThread extends Thread {
public void run() {
[Link]("Prime numbers: ");
for (int i = 2; i <= 20; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
[Link]();
}
private boolean isPrime(int num) {
if (num <= 1) return false;
for (int j = 2; j <= [Link](num); j++) {
if (num % j == 0) return false;
}
return true;
}
}
class CompositeThread extends Thread {
public void run() {
[Link]("Composite numbers: ");
for (int i = 2; i <= 20; i++) {
if (!isPrime(i)) {
[Link](i + " ");
}
}
[Link]();
}
private boolean isPrime(int num) {
if (num <= 1) return false;
for (int j = 2; j <= [Link](num); j++) {
if (num % j == 0) return false;
}
return true;
}
}
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
PrimeThread primeThread = new PrimeThread();
CompositeThread compositeThread = new CompositeThread();
[Link]();
[Link]();
}
}
[Link] the role of event sources, event objects, and listeners in Java’s event model.
Write a short Java program that changes the background color of a frame when
different buttons are clicked.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorChanger extends JFrame implements ActionListener {
private JButton redButton, greenButton, blueButton;
public ColorChanger() {
redButton = new JButton("Red");
greenButton = new JButton("Green");
blueButton = new JButton("Blue");
[Link](this);
[Link](this);
[Link](this);
JPanel panel = new JPanel();
[Link](redButton);
[Link](greenButton);
[Link](blueButton);
add(panel);
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == redButton)
getContentPane().setBackground([Link]);
else if ([Link]() == greenButton)
getContentPane().setBackground([Link]);
else if ([Link]() == blueButton)
getContentPane().setBackground([Link]);
}
public static void main(String[] args) {
new ColorChanger();
}
}
[Link] the Delegation Event Model in Java and illustrate it with a labeled
diagram. Use an adapter class and write a java program to demonstrate the mouse
click event.
• Source generates an event & sends it to one or more listeners.
• Listener simply waits until it receives an event.
• Once received, listener processes the event & returns.
• Advantage : application logic that processes event is clearly separated from the UI logic
that generates those events.
• An UI element is able to delegate the processing of an event to a separate piece of code (
Event handler)
• This is a more efficient way to handle events than the design used by the old Java 1.0
approach. Previously, an event was propagated up the containment hierarchy until it was
handled by a component.
• This required components to receive events that they did not process, and it wasted
valuable time. The delegation event model eliminates this overhead.
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseClickDemo extends JFrame {
public MouseClickDemo() {
setTitle("Mouse Click Adapter Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at: " + [Link]() + ", " + [Link]());
}
});
}
public static void main(String[] args) {
[Link](() -> {
new MouseClickDemo().setVisible(true);
});
}
}
[Link] FlowLayout, GridBagLayout, and CardLayout, describing how each
arranges components in a container. Design a Java GUI that combines GridLayout
for the top panel and BorderLayout for the main frame.
import [Link].*;
import [Link].*;
public class LayoutDemo extends JFrame {
public LayoutDemo() {
setTitle("GridLayout and BorderLayout Demo");
// Top panel with GridLayout (2 rows, 3 columns)
JPanel topPanel = new JPanel(new GridLayout(2, 3));
for (int i = 1; i <= 6; i++) {
[Link](new JButton("Button " + i));
}
// Set BorderLayout for the main frame
setLayout(new BorderLayout());
// Add top panel to the NORTH region of BorderLayout
add(topPanel, [Link]);
// Add a text area in the CENTER
add(new JTextArea("Center area"), [Link]);
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
[Link](() -> new LayoutDemo());
}
}
6. Discuss five key features of Swing that make it more powerful than AWT. Write a
Swing program that contains a text field and button; when clicked, display a message in
a label.
Five key features of Swing that make it more powerful than AWT:
1. Lightweight Components: Swing components are lightweight and written entirely in
Java, unlike AWT components which are heavyweight and depend on native operating
system components.
2. Pluggable Look and Feel: Swing supports changing the appearance dynamically
using pluggable look-and-feel, allowing consistent UI across platforms or platform-
native styles.
3. Rich Set of Components: Swing provides a comprehensive set of GUI components
such as tables, trees, sliders, tabbed panes, which are not available in AWT.
4. MVC Architecture: Swing components follow Model-View-Controller architecture
internally, separating data, presentation, and user interaction for better modularity.
5. Double Buffering: Swing uses double buffering by default, reducing flickering
during rendering and providing smoother graphics.
import [Link].*;
import [Link].*;
public class SwingDemo extends JFrame implements ActionListener {
private JTextField textField;
private JButton button;
private JLabel label;
public SwingDemo() {
setTitle("Swing TextField and Button Demo");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField = new JTextField(20);
button = new JButton("Show Message");
label = new JLabel(" ");
[Link](this);
JPanel panel = new JPanel();
[Link](textField);
[Link](button);
[Link](label);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String text = [Link]();
[Link]("You entered: " + text);
}
public static void main(String[] args) {
new SwingDemo();
}
[Link] the Applet life cycle with a neat [Link] an applet that reads a
username parameter and displays a personalized greeting.
import [Link];
import [Link].*;
public class GreetingApplet extends Applet {
String name;
public void init() {
name = getParameter("username"); // Read parameter
if (name == null) {
name = "Guest"; // Default value
}
}
public void paint(Graphics g) {
[Link]("Hello, " + name + "! Welcome to the Applet.", 20, 50);
}
}
8. Explain the structure and use of JTable and JTree in Swing. Write a program to
display a simple table with three rows and three columns inside a JScrollPane
Structure and Use of JTable in Swing
JTable is a Swing component used to display and optionally edit two-dimensional data in a
tabular format, similar to a spreadsheet. Its structure involves:
Data Model:
JTable uses a TableModel (often DefaultTableModel) to manage the underlying data. This
model defines methods for getting and setting cell values, and for notifying the table when
data changes.
Column Model:
TableColumnModel (often DefaultTableColumnModel) manages the columns, including their
width, order, and associated TableColumn objects.
Selection Model:
ListSelectionModel (often DefaultListSelectionModel) handles row and column selection.
Renderers and Editors:
JTable uses TableCellRenderer to display cell content and TableCellEditor to allow editing of
cell content. Default renderers and editors are provided for common data types.
Use: JTable is used for presenting structured data that can be viewed and potentially
manipulated by the user.
Structure and Use of JTree in Swing
JTree is a Swing component used to display hierarchical data in a tree-like structure. Its
structure involves:
Tree Model:
JTree uses a TreeModel (often DefaultTreeModel) to represent the hierarchical data. This
model defines how to get the root, children, and parent of a node, and how to detect changes
in the tree structure.
Tree Nodes:
Data within a JTree is organized into TreeNode objects (often DefaultMutableTreeNode),
which can have parent-child relationships.
Renderers:
JTree uses TreeCellRenderer to customize the appearance of individual nodes.
Use: JTree is used for displaying data with a clear parent-child relationship, such as file
systems, organizational charts, or navigation menus.
Program to Display a Simple Table
import [Link].*;
import [Link].*;
public class SimpleTableDemo extends JFrame {
public SimpleTableDemo() {
setTitle("Simple JTable Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null); // Center the window
// Column names
String[] columnNames = {"Name", "Age", "City"};
// Data for the table (3 rows, 3 columns)
Object[][] rowData = {
{"Alice", 30, "New York"},
{"Bob", 24, "London"},
{"Charlie", 35, "Paris"}
};
// Create the JTable
JTable table = new JTable(rowData, columnNames);
// Add the table to a JScrollPane for scrolling capabilities
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to the frame's content pane
add(scrollPane, [Link]);
}
public static void main(String[] args) {
[Link](() -> {
new SimpleTableDemo().setVisible(true);
});
}
}
9. Explain how to create and handle events for JButton. Demonstrate how to use
JCheckBox and JRadioButton with a small example.
Creating and Handling Events for JButton in Java Swing
JButton is a GUI button component.
To handle events (like button clicks), you register an ActionListener on the button.
Override actionPerformed method to define what happens when the button is clicked.
Using JCheckBox and JRadioButton
JCheckBox: Represents a checkbox allowing multiple selections.
JRadioButton: Represents options where only one can be selected within a group.
Radio buttons are grouped using ButtonGroup to enforce single selection.
import [Link].*;
import [Link].*;
public class SimpleButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Example");
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click");
JCheckBox checkBox = new JCheckBox("Check me");
JRadioButton radioButton = new JRadioButton("Select me");
JLabel label = new JLabel("Status will appear here");
// Add action listeners
[Link](e -> [Link]("Button clicked!"));
[Link](e -> [Link]("Checkbox " + ([Link]() ?
"checked" : "unchecked")));
[Link](e -> [Link]("Radio button selected"));
JPanel panel = new JPanel();
[Link](button);
[Link](checkBox);
[Link](radioButton);
[Link](label);
[Link](panel);
[Link](true);
}
}
10. Differentiate between multithreading and multitasking. Explain why multithreading
improves program performance. Draw and explain the thread life cycle with
appropriate method names.
Why Multithreading Improves Program Performance
Allows concurrent execution of multiple parts of a program.
Efficient resource utilization by sharing memory, reducing overhead.
Provides faster response time & better CPU utilization.
Enables real-time behavior (e.g., responsive UI, background processing).
Thread lifecycle :