0% found this document useful (0 votes)
20 views

CAT2 QB Java

The document contains a question bank with 12 multiple choice questions related to object oriented programming using Java. The questions cover topics such as threads and their states, similarities between threads and multithreading, string constructors, serialization, event handling, and drawing shapes.

Uploaded by

Abi Nesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CAT2 QB Java

The document contains a question bank with 12 multiple choice questions related to object oriented programming using Java. The questions cover topics such as threads and their states, similarities between threads and multithreading, string constructors, serialization, event handling, and drawing shapes.

Uploaded by

Abi Nesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

:

FRANCIS XAVIER ENGINEERING COLLEGE


Department of Artificial Intelligence and Data science
21IT3602 OBJECT ORIENTED PROGRAMMING USING JAVA
Question Bank

Q.No Question
1. What are the various states of a thread and write the importances of using Threads?
 New: The thread is in this state when it has been created but has not yet started.
The necessary resources are allocated, but the thread has not been scheduled for
execution.
 Runnable/Ready: The thread is ready to run, but the operating system has not
selected it to be the running thread yet. It's waiting for the CPU time.
 Blocked/Waiting: The thread is waiting for some event to occur, such as user input
or the availability of a resource. While in this state, the thread does not consume
CPU time.
 Timed Waiting: Similar to the blocked state, but with a specified waiting time.
The thread will automatically transition to the Runnable state after the specified
time.
 Terminated/Dead: The thread has completed its execution or has been explicitly
terminated. Once in this state, a thread cannot be restarted.

2. Write a simalarities between Thread and Multithreading?

Aspect Thread Multithreading

The smallest unit of execution within a Involves concurrent execution of multiple threads
Definition process. within a single process.

Each thread within a process has its own


Each thread has its own program counter, execution context, but threads share resources
Execution Context register set, and stack. like memory space and file handles.

The primary goal is to achieve concurrency by


Enables concurrent execution of tasks allowing multiple threads to execute
Concurrency within a process. simultaneously.
Multithreading facilitates communication and
Threads within a process can resource sharing between threads, promoting
Communication communicate and share resources easily. efficient collaboration.

Threads are managed by the operating Multithreading is supported by the operating


Operating System system, which provides necessary system, responsible for managing the execution
Support infrastructure. of multiple threads.

Multithreading promotes modularity and


Modularity and Threads can be used to create modular responsiveness by allowing different threads to
Responsiveness and responsive programs. perform tasks concurrently.

Multithreading improves resource utilization by


Efficient Resource Threads make more efficient use of enabling parallel execution and better utilization
Utilization system resources. of multiple cores.

Synchronization mechanisms (e.g., locks, Proper synchronization is crucial in


semaphores) can be used to coordinate multithreading to manage access to shared
Synchronization thread execution. resources and prevent conflicts.

3. What are the constructors used for creating a string with byte array?

 String(byte[] bytes):

 String(byte[] bytes, Charset charset):

4. What value is assigned to string type when it is automatically initialized and specify some
operations that are performed using string?

In Java, when a String variable is automatically initialized (for example, as a member


variable in a class or as a local variable in a method), it is assigned the value null. Unlike
primitive data types, which are assigned default values (e.g., 0 for int), objects like String
are assigned the default value of null if no explicit initialization is provided.

5 Is it possible to change an object after it has been deserialized? If yes, then how?

In Java, after an object has been deserialized, it is indeed possible to modify its state.
Deserialization is the process of reconstructing an object from its serialized form, and once
the object is reconstructed in memory, you can interact with it just like any other object.

6. When should we use serialization? Where is it useful?

Serialization is the process of converting an object into a format that can be easily stored,
transmitted, or reconstructed. It's useful in various scenarios, and here are some common
situations where serialization is employed:

7. Identify the constants associated with Adjustment Event class.

n Java, the AdjustmentEvent class is associated with constants that represent different
types of adjustment events. The constants are typically used to identify the type of
adjustment that occurred. The constants are part of the Adjustable interface, and they are
as follows:

UNIT_INCREMENT (int):

Represents a unit increment adjustment. It is usually triggered by clicking the arrow


buttons or pressing the arrow keys to increase the value.

UNIT_DECREMENT (int):

Represents a unit decrement adjustment. It is usually triggered by clicking the arrow


buttons or pressing the arrow keys to decrease the value.

BLOCK_INCREMENT (int):

Represents a block increment adjustment. It is typically triggered by clicking in the track


area above the thumb or pressing the Page Down key.

BLOCK_DECREMENT (int):

Represents a block decrement adjustment. It is typically triggered by clicking in the track


area below the thumb or pressing the Page Up key.

8. Which package contains the methods to receive and process events and the method that support
the events?

In Java, the java.awt package contains classes and interfaces related to Abstract
Window Toolkit (AWT), which is a part of the Java Foundation Classes (JFC). This
package includes methods to receive and process events, as well as methods that
support events.
Key classes and interfaces related to events in the java.awt package include:

1. Component Class:
 The Component class is a fundamental part of AWT and Swing.
Components can generate various events, and it provides methods for
event registration and handling.
2. Container Class:
 The Container class extends Component and represents a container
of components. It also plays a role in the event-handling mechanism.
3. Event Class:
 The Event class is part of the AWT event model, and it represents an
event that can occur within a graphical user interface. However, note that as
of Java 1.1, the event-delegation model is recommended, and the Event
class is considered obsolete.
4. EventListener Interface:
 The EventListener interface is the base interface for all event
listener interfaces. It doesn't declare any methods but serves as a tag
interface for event listener objects.
9. How to place controls in a window and remove controls from a window?

In Java, placing controls (components) in a window is typically done using layout


managers. Layout managers help in arranging components within a container, such as a
JFrame or JPanel. Here's a basic example of how you can create a window, add controls to
it, and remove controls from it:

10. Which event is generated during checkbox operations?

In Java, checkbox operations generate ItemEvent events. The ItemEvent class is part of the Java
AWT (Abstract Window Toolkit) and Swing event model. It is used to handle events related to
items, such as checkboxes, radio buttons, and choice components.

When a user interacts with a checkbox, for example by clicking on it to toggle its state, an
ItemEvent is generated. This event is then sent to registered listeners, allowing your application
to respond to the checkbox state change.

11. List the various methods available for drawing polygons, ellipses, arcs.

In Java, drawing polygons, ellipses, and arcs can be accomplished using the Graphics class, which
provides various methods for rendering shapes on a graphical component (e.g., JPanel, Canvas).
Below are some of the commonly used methods for drawing polygons, ellipses, and arcs:
Drawing Polygons:

drawPolygon(int[] xPoints, int[] yPoints, int n) and fillPolygon(int[] xPoints, int[] yPoints, int n):

12 What is the difference between init() and start() method?

In Java applets, the init() and start() methods are part of the applet lifecycle,
and they serve different purposes:

1. init() Method:
 The init() method is called when an applet is first created. It is
responsible for initializing the applet and is typically used to perform one-
time setup tasks. This method is called after the applet is instantiated but
before it is displayed on the screen.

Q.No Question

11 (a) Develop an application to show multithreaded program


to show hours, minutes and seconds on separate
threads.
The MultithreadedClock class extends JFrame and
creates a simple GUI with labels for hours, minutes,
and seconds.
Three threads (hoursThread, minutesThread,
secondsThread) are created, each responsible for
updating a specific time component.
The TimeThread class is a nested class that extends
Thread and is responsible for continuously updating the
corresponding label text.
The run() method of each thread updates the label text
every second and sleeps for 1000 milliseconds between
updates.
The main method of the MultithreadedClock class
creates an instance of the application, ensuring it's
executed on the Event Dispatch Thread (EDT) using
SwingUtilities.invokeLater().
Please note that this example uses Swing components
for simplicity. In a real-world application, you might
want to consider using javax.swing.Timer for updating
GUI components at regular intervals instead of
manually creating and managing threads.
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MultithreadedClock extends JFrame {

private JLabel hoursLabel, minutesLabel,


secondsLabel;

public MultithreadedClock() {
setTitle("Multithreaded Clock");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
setSize(300, 150);
setLayout(new FlowLayout());

hoursLabel = new JLabel("Hours: ");


minutesLabel = new JLabel("Minutes: ");
secondsLabel = new JLabel("Seconds: ");

add(hoursLabel);
add(minutesLabel);
add(secondsLabel);

// Create and start threads


Thread hoursThread = new
TimeThread(Calendar.HOUR_OF_DAY, "HH");
Thread minutesThread = new
TimeThread(Calendar.MINUTE, "mm");
Thread secondsThread = new
TimeThread(Calendar.SECOND, "ss");

hoursThread.start();
minutesThread.start();
secondsThread.start();
}

private class TimeThread extends Thread {


private int calendarField;
private String format;

public TimeThread(int calendarField, String


format) {
this.calendarField = calendarField;
this.format = format;
}

@Override
public void run() {
try {
while (true) {
Calendar calendar =
Calendar.getInstance();
int timeValue =
calendar.get(calendarField);
String timeString = new
SimpleDateFormat(format).format(calendar.getTime())
;

if (calendarField ==
Calendar.HOUR_OF_DAY) {
hoursLabel.setText("Hours: " +
timeString);
} else if (calendarField ==
Calendar.MINUTE) {
minutesLabel.setText("Minutes: " +
timeString);
} else if (calendarField ==
Calendar.SECOND) {
secondsLabel.setText("Seconds: " +
timeString);
}

Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new MultithreadedClock().setVisible(true);
});
}
}

2 Design two threads to display odd numbered element in


an array of size 50 and even numbered element in
another array of size 50.Create instances of the
abovethread and run them.
public class OddEvenThreadExample {

public static void main(String[] args) {


int[] array = new int[100];

// Initialize the array with numbers 1 to 100


for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}

// Create instances of the OddThread and


EvenThread
OddThread oddThread = new OddThread(array);
EvenThread evenThread = new
EvenThread(array);

// Start the threads


oddThread.start();
evenThread.start();
}
}

class OddThread extends Thread {


private int[] array;

public OddThread(int[] array) {


this.array = array;
}

@Override
public void run() {
System.out.println("Odd Thread:");
for (int i = 0; i < array.length; i += 2) {
System.out.print(array[i] + " ");
try {
Thread.sleep(100); // Sleep for a short
duration for better readability of output
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class EvenThread extends Thread {


private int[] array;

public EvenThread(int[] array) {


this.array = array;
}

@Override
public void run() {
System.out.println("\nEven Thread:");
for (int i = 1; i < array.length; i += 2) {
System.out.print(array[i] + " ");
try {
Thread.sleep(100); // Sleep for a short
duration for better readability of output
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
 } The OddEvenThreadExample class
initializes an array of size 100 with numbers
from 1 to 100.
 The OddThread class extends Thread
and is responsible for printing odd-
numbered elements from the array.
 The EvenThread class extends Thread
and is responsible for printing even-
numbered elements from the array.
 Both threads start simultaneously, and
the output may vary on each run due to
thread scheduling.

The program uses simple thread


synchronization with Thread.sleep(100) to
improve the readability of the output by
introducing a slight delay between printed
numbers. Keep in mind that the exact output
may vary due to the concurrent nature of
threads.

3. Write a Java program that reads a .txt file from user


and display number of words and lines in the file
. import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileWordLineCounter {

public static void main(String[] args) {


// Prompt the user for the file path
System.out.print("Enter the path of the .txt file: ");
String filePath = System.console().readLine();

try {
// Read the file
FileReader fileReader = new
FileReader(filePath);
BufferedReader bufferedReader = new
BufferedReader(fileReader);

int wordCount = 0;
int lineCount = 0;
// Read each line from the file
String line;
while ((line = bufferedReader.readLine()) !=
null) {
// Count lines
lineCount++;

// Tokenize the line to count words


StringTokenizer tokenizer = new
StringTokenizer(line);
wordCount += tokenizer.countTokens();
}

// Close the readers


bufferedReader.close();
fileReader.close();

// Display the results


System.out.println("Number of words: " +
wordCount);
System.out.println("Number of lines: " +
lineCount);

} catch (IOException e) {
System.err.println("Error reading the file: " +
e.getMessage());
}
} The user is prompted to enter the path of a .txt file.
The program then uses FileReader and BufferedReader
to read the file line by line.
For each line, it increments the line count.
It uses StringTokenizer to count the number of words
in each line and increments the total word count.
Finally, it displays the number of words and lines in the
file.
}

Analyze the various purpose of streams and also


4. explain the various methods of reader and writer
abstract classes?

Streams in Java are a powerful and flexible abstraction


for reading from and writing to different kinds of I/O
devices. They provide a uniform way to handle input
and output operations, regardless of the underlying data
source or destination. Streams play a crucial role in
Java I/O operations, enabling efficient and versatile
handling of data. Purpose of Streams:

Abstraction:

Streams provide a high-level abstraction for I/O


operations, allowing developers to interact with data
sources and destinations in a consistent manner.

Efficiency:

Streams support buffered I/O, which helps in reducing


the number of physical I/O operations. This buffering
mechanism improves performance by reducing the
overhead associated with individual read and write
operations.

Flexibility:

Streams can be connected, chained, and composed to


create complex I/O workflows. This flexibility allows
developers to build sophisticated pipelines for
processing data.

Standardization:

The Java I/O API standardizes the way data is read


from and written to various sources, such as files,
network connections, and in-memory buffers.

Uniformity:

Whether reading from a file, writing to a socket, or


working with any other data source, the stream API
provides a uniform interface. This uniformity simplifies
code and makes it easier to switch between different
I/O sources.

Reader and Writer Abstract Classes:

In Java, the Reader and Writer abstract classes are part


of the Java I/O hierarchy and are used for character-
based I/O operations. Below are some of the common
methods provided by these abstract classes:

Methods in the Reader Class:

int read() throws IOException:

Reads a single character. Returns the character read, or


-1 if the end of the stream has been reached.

int read(char[] cbuf) throws IOException:

Reads characters into an array. Returns the number of


characters read, or -1 if the end of the stream has been
reached.

int read(char[] cbuf, int off, int len) throws


IOException:

Reads characters into a portion of an array. Returns the


number of characters read, or -1 if the end of the stream
has been reached.

long skip(long n) throws IOException:

Skips characters. Returns the number of characters


skipped.

boolean ready() throws IOException:

Returns true if the stream is ready to be read.

boolean markSupported():

Returns true if the stream supports the mark and reset


methods.

void mark(int readAheadLimit) throws IOException:


Marks the present position in the stream.

void reset() throws IOException:

Resets the stream to the most recent mark.

void close() throws IOException:

Closes the stream.

Methods in the Writer Class:

void write(int c) throws IOException:

Writes a single character.

void write(char[] cbuf) throws IOException:

Writes an array of characters.

void write(char[] cbuf, int off, int len) throws


IOException:

Writes a portion of an array of characters.

void write(String str) throws IOException:

Writes a string.

void write(String str, int off, int len) throws


IOException:

Writes a portion of a string.

void flush() throws IOException:

Flushes the stream.

void close() throws IOException:


Closes the stream.

These methods provide a foundation for building


various concrete Reader and Writer implementations,
allowing developers to handle character-based I/O
operations in a standardized way. The concrete classes
that extend these abstract classes include FileReader,
FileWriter, BufferedReader, BufferedWriter, and more.

5. Write a Java program to count the number of


vowels,consonants,letters and digits in a string? import
java.util.Scanner;

public class StringCharacterCounter {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a string


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Close the scanner


scanner.close();

// Call the method to count characters


countCharacters(inputString);
}

private static void countCharacters(String


inputString) {
// Initialize counters
int vowelCount = 0;
int consonantCount = 0;
int letterCount = 0;
int digitCount = 0;

// Convert the input string to lowercase for case-


insensitive counting
String lowercaseString =
inputString.toLowerCase();

// Iterate through each character in the string


for (int i = 0; i < lowercaseString.length(); i++) {
char currentChar = lowercaseString.charAt(i);
// Check if the character is a letter
if (Character.isLetter(currentChar)) {
letterCount++;

// Check if the letter is a vowel


if (isVowel(currentChar)) {
vowelCount++;
} else {
consonantCount++;
}
}
// Check if the character is a digit
else if (Character.isDigit(currentChar)) {
digitCount++;
}
}

// Display the results


System.out.println("Number of vowels: " +
vowelCount);
System.out.println("Number of consonants: " +
consonantCount);
System.out.println("Number of letters: " +
letterCount);
System.out.println("Number of digits: " +
digitCount);
}

private static boolean isVowel(char c) {


// Check if the character is a vowel
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c ==
'u';
}
}
(OR)

(b) Write a Java program to find the number of words in a


string?
import java.util.Scanner;

public class WordCount {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Close the scanner


scanner.close();

// Call the method to count words


int wordCount = countWords(inputString);

// Display the result


System.out.println("Number of words: " +
wordCount);
}

private static int countWords(String inputString) {


// Check for empty or null string
if (inputString == null ||
inputString.trim().isEmpty()) {
return 0;
}

// Split the string into words using whitespace as


the delimiter
String[] words = inputString.split("\\s+");

// Return the number of words


return words.length;
}
} In this program:

The user is prompted to enter a string.


The program then calls the countWords method to find
the number of words in the string.
The countWords method uses the split method with the
regular expression \\s+ to split the string into an array
of words based on whitespace.
The length of the resulting array gives the number of
words.
Note: This program considers any sequence of non-
whitespace characters as a word. If you have specific
requirements for what constitutes a word (e.g.,
excluding punctuation), you may need to adjust the
splitting logic accordingly.
8. Write an AWT GUI Application. Each time the
“Count” button is clicked, the counter value will be
increased by 1?

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class CounterApp extends Frame {

private int counter = 0;

private Label counterLabel;

public CounterApp() {

// Set the layout manager

setLayout(new FlowLayout());

// Create and add components

Button countButton = new Button("Count");

counterLabel = new Label("Counter: " + counter);

add(countButton);

add(counterLabel);

// Add action listener to the button

countButton.addActionListener(new
ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Increment the counter and update the label

counter++;

counterLabel.setText("Counter: " + counter);

}
});

// Set frame properties

setTitle("Counter Application");

setSize(300, 150);

setVisible(true);

// Handle window close event

addWindowListener(new
java.awt.event.WindowAdapter() {

public void
windowClosing(java.awt.event.WindowEvent
windowEvent) {

System.exit(0);

});

public static void main(String[] args) {

new CounterApp();

9. Develop a java program to implement a 3 frame in a


window .In each frame create rectangle and fill each
with color, texture and gradient?

import javax.swing.*;

import java.awt.*;

import java.awt.geom.Rectangle2D;

public class ThreeFrameExample {


public ThreeFrameExample() {

JFrame frame = new JFrame("Three Frames Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new GridLayout(1, 3));

// Frame 1: Color-filled Rectangle

JPanel colorFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.BLUE);

g2d.fillRect(10, 10, 80, 80);

};

frame.add(colorFrame);

// Frame 2: Texture-filled Rectangle

JPanel textureFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

TexturePaint texturePaint = createTexturePaint();

g2d.setPaint(texturePaint);

g2d.fillRect(10, 10, 80, 80);

}
private TexturePaint createTexturePaint() {

BufferedImage textureImage = new


BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = textureImage.createGraphics();

g2d.setColor(Color.YELLOW);

g2d.fillRect(0, 0, 10, 10);

g2d.setColor(Color.BLACK);

g2d.drawRect(0, 0, 9, 9);

g2d.dispose();

return new TexturePaint(textureImage, new


Rectangle2D.Double(0, 0, 10, 10));

};

frame.add(textureFrame);

// Frame 3: Gradient-filled Rectangle

JPanel gradientFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

GradientPaint gradientPaint = new


GradientPaint(10, 10, Color.RED, 90, 90, Color.GREEN);

g2d.setPaint(gradientPaint);

g2d.fillRect(10, 10, 80, 80);

};

frame.add(gradientFrame);
frame.setSize(300, 120);

frame.setVisible(true);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new


ThreeFrameExample());

8. Write a java program to implement a 3 frame in a


window, In each frame create rectangle and fill each
one with (i) color (ii) texture and (iii) gradient.

import javax.swing.*;

import java.awt.*;

import java.awt.geom.Rectangle2D;

import java.awt.image.BufferedImage;

public class ThreeFrameExample {

public ThreeFrameExample() {

JFrame frame = new JFrame("Three Frames


Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);

frame.setLayout(new GridLayout(1, 3));

// Frame 1: Color-filled Rectangle

JPanel colorFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {


super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.BLUE);

g2d.fillRect(10, 10, 80, 80);

};

frame.add(colorFrame);

// Frame 2: Texture-filled Rectangle

JPanel textureFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

TexturePaint texturePaint =
createTexturePaint();

g2d.setPaint(texturePaint);

g2d.fillRect(10, 10, 80, 80);

private TexturePaint createTexturePaint() {

BufferedImage textureImage = new


BufferedImage(10, 10,
BufferedImage.TYPE_INT_RGB);

Graphics2D g2d =
textureImage.createGraphics();

g2d.setColor(Color.YELLOW);

g2d.fillRect(0, 0, 10, 10);

g2d.setColor(Color.BLACK);

g2d.drawRect(0, 0, 9, 9);
g2d.dispose();

return new TexturePaint(textureImage, new


Rectangle2D.Double(0, 0, 10, 10));

};

frame.add(textureFrame);

// Frame 3: Gradient-filled Rectangle

JPanel gradientFrame = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

GradientPaint gradientPaint = new


GradientPaint(10, 10, Color.RED, 90, 90,
Color.GREEN);

g2d.setPaint(gradientPaint);

g2d.fillRect(10, 10, 80, 80);

};

frame.add(gradientFrame);

frame.setSize(300, 120);

frame.setVisible(true);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new


ThreeFrameExample());

}
}

9. Write a java program to implement event handling by


implementing ActionListener?

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ActionListenerExample implements


ActionListener {

private JFrame frame;

private JButton clickButton;

public ActionListenerExample() {

// Create the frame

frame = new JFrame("ActionListener Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);

// Create the button

clickButton = new JButton("Click Me");

// Add ActionListener to the button

clickButton.addActionListener(this);

// Add the button to the frame


frame.getContentPane().add(BorderLayout.CENTER,
clickButton);

// Set frame properties

frame.setSize(300, 200);

frame.setVisible(true);

// Implementing ActionListener method

@Override

public void actionPerformed(ActionEvent e) {

// This method is called when the button is clicked

JOptionPane.showMessageDialog(frame, "Button
Clicked!");

public static void main(String[] args) {

SwingUtilities.invokeLater(ActionListenerExample::ne
w);

} The ActionListenerExample class implements the


ActionListener interface.

The clickButton is a JButton that triggers an action


event when clicked.

The ActionListenerExample class itself is registered as


an ActionListener for the button using
clickButton.addActionListener(this).

The actionPerformed method is implemented to handle


the action event. In this case, it displays a simple
message using JOptionPane.

When you run this program, a window with a button


("Click Me") will appear. Clicking the button will
trigger the actionPerformed method, and a message
dialog will be displayed.

11. Develop a Java program to implement the following


Create four check boxes. The initial state of the first
box should be in checked state. The status of each
check box should be displayed. When we change the
state of a check box, the status should be displayed and
updated.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckBoxExample {

private JFrame frame;


private JCheckBox checkBox1, checkBox2,
checkBox3, checkBox4;
private JLabel statusLabel;

public CheckBoxExample() {
// Create the frame
frame = new JFrame("CheckBox Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
frame.setLayout(new FlowLayout());

// Create the checkboxes


checkBox1 = new JCheckBox("CheckBox 1",
true); // Checked by default
checkBox2 = new JCheckBox("CheckBox 2");
checkBox3 = new JCheckBox("CheckBox 3");
checkBox4 = new JCheckBox("CheckBox 4");

// Add ActionListener to handle checkbox state


changes
checkBox1.addActionListener(new
CheckBoxListener());
checkBox2.addActionListener(new
CheckBoxListener());
checkBox3.addActionListener(new
CheckBoxListener());
checkBox4.addActionListener(new
CheckBoxListener());

// Create the status label


statusLabel = new JLabel("Status: CheckBox 1 is
checked.");
// Add components to the frame
frame.add(checkBox1);
frame.add(checkBox2);
frame.add(checkBox3);
frame.add(checkBox4);
frame.add(statusLabel);

// Set frame properties


frame.setSize(300, 150);
frame.setVisible(true);
}

// ActionListener to handle checkbox state changes


private class CheckBoxListener implements
ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Display the status based on checkbox state
String status = "Status: ";
status += checkBox1.isSelected() ? "CheckBox
1 is checked." : "CheckBox 1 is unchecked.";
status += " | ";
status += checkBox2.isSelected() ? "CheckBox
2 is checked." : "CheckBox 2 is unchecked.";
status += " | ";
status += checkBox3.isSelected() ? "CheckBox
3 is checked." : "CheckBox 3 is unchecked.";
status += " | ";
status += checkBox4.isSelected() ? "CheckBox
4 is checked." : "CheckBox 4 is unchecked.";

statusLabel.setText(status);
}
}

public static void main(String[] args) {

SwingUtilities.invokeLater(CheckBoxExample::new);
}
 } Four checkboxes (checkBox1, checkBox2,
checkBox3, checkBox4) are created using
JCheckBox.
 An ActionListener (CheckBoxListener) is
implemented to handle checkbox state changes.
 The status label (statusLabel) is updated
based on the state of each checkbox.
 The program uses a simple FlowLayout for
arranging components.

When you run this program, you will see a window


with four checkboxes, and the status label initially
shows the state of the checkboxes. When you
change the state of any checkbox, the status label
will be updated accordingly.

12. Develop a Java program to display the following picture as


Output using Applet viewer and discuss its coordinates ?

You might also like