Question 6-10
Create an enum Weekday in Java and write a program to display the name and ordinal value of each constant in the enum.
Write a Java program to sort an ArrayList of strings in ascending and descending order using lambda expressions.
Write a program to demonstrate client-server communication using UDP. Explain how the server listens for and processes client messages.
Write a Java program to demonstrate event handling using the delegation event model. Handle a button click event in a simple GUI.
Explain the role of adapter classes in Java. Write a program to handle mouse events using an adapter class.
6. Enum Weekday
Program
This program defines an enumeration for the days of the week and then iterates through its constants to display their names and ordinal (positional) values.
Explanation
enum Weekday
: This defines a special typeWeekday
that can only have one of the seven specified values (SUNDAY
,MONDAY
, etc.).Weekday.values()
: This is a built-in method that returns an array containing all the constants of the enum in the order they are declared.for-each
loop: We loop through the array provided byvalues()
..name()
: This method returns the name of the enum constant as aString
(e.g., "SUNDAY")..ordinal()
: This method returns the zero-based index of the constant (e.g.,SUNDAY
is 0,MONDAY
is 1).
Java Code
/**
* 6. Create an enum Weekday and display its constants.
*/
// Define the enumeration for the days of the week
enum Weekday {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
public class WeekdayEnumDemo {
public static void main(String[] args) {
System.out.println("--- Weekday Enum Constants ---");
// Loop through all the constants in the Weekday enum
for (Weekday day : Weekday.values()) {
// Print the name and the ordinal value of each constant
System.out.println("Constant: " + day.name() + ", Ordinal Value: " + day.ordinal());
}
}
}
Expected Output
--- Weekday Enum Constants ---
Constant: SUNDAY, Ordinal Value: 0
Constant: MONDAY, Ordinal Value: 1
Constant: TUESDAY, Ordinal Value: 2
Constant: WEDNESDAY, Ordinal Value: 3
Constant: THURSDAY, Ordinal Value: 4
Constant: FRIDAY, Ordinal Value: 5
Constant: SATURDAY, Ordinal Value: 6
7. Sort ArrayList
Using Lambda Expressions
This program creates an ArrayList
of strings and then uses lambda expressions with the sort()
method to sort it in both ascending and descending order.
Explanation
ArrayList
: We create a standardArrayList
and add some strings to it.list.sort()
: This method sorts the list in place. It takes aComparator
as an argument. A lambda expression is a perfect way to provide a simple, on-the-fly comparator.- Ascending Sort: The lambda
(s1, s2) -> s1.compareTo(s2)
provides the natural sorting order for strings.s1.compareTo(s2)
returns a negative integer, zero, or a positive integer ifs1
is less than, equal to, or greater thans2
. - Descending Sort: To reverse the order, we simply flip the comparison in the lambda:
(s2, s1) -> s2.compareTo(s1)
. This tells thesort
method to treat "greater" elements as "smaller," effectively reversing the sort.
Java Code
import java.util.ArrayList;
import java.util.Arrays;
/**
* 7. Sort an ArrayList using lambda expressions.
*/
public class LambdaSortDemo {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Cherry", "Apple", "Elderberry", "Banana", "Date"));
// --- 1. Sort in Ascending (Alphabetical) Order ---
System.out.println("Original list: " + fruits);
// Use a lambda expression for the comparator
fruits.sort((s1, s2) -> s1.compareTo(s2));
System.out.println("Sorted in Ascending Order: " + fruits);
// --- 2. Sort in Descending Order ---
// Use a lambda that reverses the comparison
fruits.sort((s1, s2) -> s2.compareTo(s1));
System.out.println("Sorted in Descending Order: " + fruits);
}
}
Expected Output
Original list: [Cherry, Apple, Elderberry, Banana, Date]
Sorted in Ascending Order: [Apple, Banana, Cherry, Date, Elderberry]
Sorted in Descending Order: [Elderberry, Date, Cherry, Banana, Apple]
8. UDP Client-Server Communication
This program demonstrates a connectionless client-server interaction. The server waits for a message, and the client sends one and receives a confirmation.
Explanation
- UDP (User Datagram Protocol): It is a "connectionless" protocol. Unlike TCP, no dedicated connection is established. Data is sent in packets called datagrams. Delivery is not guaranteed, nor is the order of arrival.
DatagramSocket
: This is the endpoint for sending and receiving datagrams. The server listens on a well-known port (e.g., 9876), while the client can use any available port.DatagramPacket
: This object contains the data to be sent or is used as a buffer to receive data. It also holds the IP address and port number of the sender/receiver.- Server Flow:
- Creates a
DatagramSocket
to listen on port 9876. - Waits in a loop using
socket.receive()
, which blocks until a packet arrives. - Processes the received packet, extracts the message, and prints it.
- Gets the client's address and port from the packet to send a response back.
- Creates a
- Client Flow:
- Creates a
DatagramSocket
. - Creates a message and places it in a
DatagramPacket
addressed to the server (e.g.,localhost
on port 9876). - Sends the packet using
socket.send()
. - Waits for the server's reply using
socket.receive()
.
- Creates a
Java Code
You need to run the UDPServer
first, then run the UDPClient
.
UDPServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
public static void main(String[] args) throws Exception {
// Create a socket to listen on port 9876
DatagramSocket serverSocket = new DatagramSocket(9876);
System.out.println("UDP Server is running and waiting for a client...");
byte[] receiveData = new byte[1024];
while (true) { // Run indefinitely
// Create a packet to receive data
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
// Block and wait to receive a packet from a client
serverSocket.receive(receivePacket);
// Convert the received data into a string
String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RECEIVED FROM CLIENT: " + clientMessage);
// Get the client's IP address and port from the received packet
InetAddress clientIP = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
// Create a response message and send it back to the client
String responseMessage = "Message received successfully!";
byte[] sendData = responseMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIP, clientPort);
serverSocket.send(sendPacket);
}
}
}
UDPClient.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPClient {
public static void main(String[] args) throws Exception {
// Create a client socket
DatagramSocket clientSocket = new DatagramSocket();
// Get the server's IP address (localhost in this case)
InetAddress serverIP = InetAddress.getByName("localhost");
System.out.print("Enter message to send to server: ");
Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();
// Convert the message to a byte array
byte[] sendData = message.getBytes();
// Create a packet to send to the server on port 9876
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIP, 9876);
clientSocket.send(sendPacket);
System.out.println("Message sent to the server.");
// Wait for the response from the server
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
// Print the server's response
String serverResponse = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RESPONSE FROM SERVER: " + serverResponse);
clientSocket.close();
scanner.close();
}
}
9. Event Handling with Delegation Event Model
This program creates a simple GUI with a button. When the button is clicked, a message is printed to the console.
Explanation
The Delegation Event Model has three components:
- Event Source: The object that generates an event (e.g., the
JButton
). - Event Listener: An object that wants to be notified when an event occurs. It must implement the appropriate listener interface (e.g.,
ActionListener
). - Event Object: An object that encapsulates information about the event (e.g.,
ActionEvent
).
The source delegates the task of handling an event to the registered listener.
Java Code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Demonstrates the Delegation Event Model by handling a button click.
* The main class itself acts as the ActionListener.
*/
public class ButtonClickDemo implements ActionListener {
public ButtonClickDemo() {
// 1. Create the components (the sources)
JFrame frame = new JFrame("Event Handling Demo");
JButton button = new JButton("Click Me!");
// 2. Register the listener with the source.
// 'this' refers to the ButtonClickDemo instance, which is an ActionListener.
button.addActionListener(this);
// Standard frame setup
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.getContentPane().add(button); // Add button to the frame
frame.setVisible(true);
}
/**
* 3. Implement the listener interface method.
* This is the code that will be executed when the event occurs.
*/
@Override
public void actionPerformed(ActionEvent e) {
// The Event Object 'e' can give information, like the source
System.out.println("Button was clicked! Event source: " + e.getActionCommand());
}
public static void main(String[] args) {
// Create an instance of our GUI application
new ButtonClickDemo();
}
}
Expected Output
When you run the program, a window with a button appears. Every time you click the button, the following message is printed to your console:
Button was clicked! Event source: Click Me!
10. Adapter Classes for Event Handling
This program demonstrates how an adapter class simplifies handling mouse events.
Explanation
Role of Adapter Classes: Listener interfaces like MouseListener
or WindowListener
contain multiple methods. If you only need to handle one or two of these events, you still have to provide empty implementations for all other methods in the interface. This leads to boilerplate code.
An adapter class is an abstract class that provides default (empty) implementations for all methods in a listener interface. You can extend the adapter class and override only the methods you are interested in. This makes your code much cleaner.
In this example, we extend MouseAdapter
so we only have to implement mouseClicked
, not all five methods of MouseListener
.
Java Code
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseAdapterDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Adapter Demo");
JLabel label = new JLabel("Click or move mouse here!", SwingConstants.CENTER);
// Use an anonymous inner class that extends MouseAdapter
label.addMouseListener(new MouseAdapter() {
/**
* We only override the method we need, thanks to MouseAdapter.
*/
@Override
public void mouseClicked(MouseEvent e) {
// Get the x and y coordinates from the MouseEvent object
String message = "Mouse clicked at (" + e.getX() + ", " + e.getY() + ")";
label.setText(message);
System.out.println(message);
}
});
// Standard frame setup
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(label);
frame.setVisible(true);
}
}```
#### Expected Output
A window appears with a label. When you click anywhere on the label, the label text updates to show the coordinates of the click, and a corresponding message is printed to the console.
**Label Text after a click:**
`Mouse clicked at (150, 125)`
**Console Output:**
Mouse clicked at (150, 125)