V. Write a Java program to demonstrate the working of different collection classes.
[Use
package structure to store multiple classes].
To demonstrate the working of different collection classes in Java, we'll create a Java program that
uses various collection classes like `ArrayList`, `HashSet`, `HashMap`, and `LinkedList`.
- ArrayList Example (`[Link]`): Demonstrates adding, accessing, checking, and removing
elements from an `ArrayList`. It allows duplicates and maintains insertion order.
- HashSet Example (`[Link]`): Demonstrates adding, checking, and removing elements
from a `HashSet`. It does not allow duplicates and does not maintain any specific order.
- HashMap Example (`[Link]`): Demonstrates adding, accessing, checking, and removing
key-value pairs from a `HashMap`. It allows null keys and values and does not maintain any
specific order.
Project Structure:
src/
└── collectionsdemo/
├── [Link]
├── [Link]
├── [Link]
└── [Link]
1. `[Link]`
This is the main class that will call other classes to demonstrate the working of different collections.
package collectionsdemo; public class
CollectionExample { public static
void main(String[] args) {
[Link]();
[Link]();
[Link]();
}
}
2. `[Link]`
This class demonstrates the usage of `ArrayList`.
package collectionsdemo; import
[Link]; import [Link];
public class ListExample { public static
void demoArrayList()
{ [Link]("ArrayList
Example:"); List<String> arrayList = new
ArrayList<>(); [Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple"); // Duplicate element
for (String fruit : arrayList) {
[Link](fruit);
}
[Link]("Size of ArrayList: " + [Link]());
[Link]("Is 'Banana' present? " +
[Link]("Banana")); [Link]("Removing
'Apple'..."); [Link]("Apple");
[Link]("ArrayList after removal:");
for (String fruit : arrayList) {
[Link](fruit);
}
[Link]();
}
}
3. `[Link]`
This class demonstrates the usage of `HashSet`.
package collectionsdemo; import [Link]; import
[Link]; public class SetExample { public static void
demoHashSet() { [Link]("HashSet
Example:"); Set<String> hashSet = new HashSet<>();
[Link]("Apple"); [Link]("Banana");
[Link]("Orange"); [Link]("Apple"); //
Duplicate element, won't be added for (String fruit :
hashSet) {
[Link](fruit);
}
[Link]("Size of HashSet: " + [Link]());
[Link]("Is 'Banana' present? " +
[Link]("Banana")); [Link]("Removing
'Orange'..."); [Link]("Orange");
[Link]("HashSet after removal:");
for (String fruit : hashSet) {
[Link](fruit);
}
[Link]();
}
}
4. `[Link]`
This class demonstrates the usage of `HashMap`.
package collectionsdemo; import
[Link]; import
[Link]; public class
MapExample { public static void
demoHashMap() {
[Link]("HashMap Example:");
Map<Integer, String> hashMap = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");
[Link](1, "Grapes"); // Replaces the value for key 1 for
([Link]<Integer, String> entry : [Link]()) {
[Link]("Key: " + [Link]() + ", Value: " + [Link]());
}
[Link]("Size of HashMap: " + [Link]());
[Link]("Is key 2 present? " +
[Link](2)); [Link]("Removing key
3..."); [Link](3);
[Link]("HashMap after removal:"); for
([Link]<Integer, String> entry : [Link]()) {
[Link]("Key: " + [Link]() + ", Value: " + [Link]());
}
[Link]();
}
}
How to Run:
1. Compile the classes from the `src` directory: javac collectionsdemo/*.java
2. Run the `CollectionExample` class:
java
[Link]
Output:
ArrayList Example:
Apple
Banana
Orange
Apple
Size of ArrayList: 4
Is 'Banana' present? true Removing 'Apple'...
ArrayList after removal:
Banana
Orange
Apple
HashSet
Example:
Apple
Banana
Orange
Size of HashSet: 3 Is
'Banana' present? true
Removing 'Orange'...
HashSet after removal:
Apple
Banana
HashMap Example:
Key: 1, Value: Grapes
Key: 2, Value: Banana
Key: 3, Value: Orange
Size of HashMap: 3
Is key 2 present? true
Removing key 3...
HashMap after removal:
Key: 1, Value: Grapes
Key: 2, Value: Banana
VI. Write a program to synchronize the threads acting on the same object. [Consider the example of
any reservations like railway, bus, movie ticket booking, etc.]
To demonstrate thread synchronization in Java, let's consider a simple example of a movie ticket
booking system where multiple threads are trying to book tickets simultaneously. We need to ensure
that the ticket booking process is synchronized so that no two threads can book the same ticket at the
same time.
Program: Synchronized Movie Ticket Booking-
Key Points:
- Synchronization: The `synchronized` keyword ensures that only one thread can execute the
`bookTicket` method at a time.
- Race Conditions: Without synchronization, multiple threads might book the same tickets
simultaneously, leading to inconsistent state and incorrect ticket counts.
- Thread Safety: The program ensures thread safety by synchronizing the critical section of code
that modifies the shared resource (`availableTickets`).
The following classes has to be define-
1. TicketBooking Class:
- This class manages the available tickets and provides a method `bookTicket` to book tickets.
- The `bookTicket` method is marked as `synchronized`, which means only one thread can execute
this method at a time. This ensures that if one thread is booking a ticket, others have to wait until
it's done.
2. TicketBookingThread Class:
- This class extends `Thread` and represents a user trying to book tickets.
- It takes the `TicketBooking` object, the passenger's name, and the number of tickets to book as
parameters.
- In the `run` method, it calls the `bookTicket` method on the shared `TicketBooking` object.
3. SynchronizedTicketBooking (Main Class):
- This class creates a `TicketBooking` object with 5 available tickets.
- It then creates three threads (`t1`, `t2`, `t3`) to simulate three users trying to book tickets
concurrently.
- The threads are started, and they attempt to book tickets. Due to the `synchronized` keyword, the
booking process will be thread-safe.
class TicketBooking
{ private int
availableTickets; public
TicketBooking(int
availableTickets)
{ [Link] =
availableTickets;
}
// Synchronized method to ensure only one thread can book a ticket at a time public
synchronized void bookTicket(String passengerName, int numberOfTickets) { if
(numberOfTickets <= availableTickets) {
[Link](passengerName + " booked " + numberOfTickets + " ticket(s).");
availableTickets -= numberOfTickets;
[Link]("Tickets left: " + availableTickets);
} else {
[Link]("Sorry, " + passengerName + ". Not enough tickets available.");
}
}
} class TicketBookingThread extends Thread { private TicketBooking ticketBooking; private
String passengerName; private int numberOfTickets; public
TicketBookingThread(TicketBooking ticketBooking, String passengerName, int
numberOfTickets) { [Link] = ticketBooking; [Link] =
passengerName; [Link] = numberOfTickets;
}
@Override
public void run()
{ [Link](passengerName,
numberOfTickets);
} } public class
SynchronizedTicketBooking
{ public static void
main(String[] args) {
// Assume there are 5 tickets available initially
TicketBooking ticketBooking = new TicketBooking(5);
// Creating multiple threads to book tickets
TicketBookingThread t1 = new
TicketBookingThread(ticketBooking, "Alice", 2);
TicketBookingThread t2 = new TicketBookingThread(ticketBooking, "Bob", 2);
TicketBookingThread t3 = new TicketBookingThread(ticketBooking, "Charlie", 2);
// Start the threads
[Link]();
[Link]();
[Link]();
}
}
Output:
Alice booked 2 ticket(s).
Tickets left: 3
Bob booked 2 ticket(s).
Tickets left: 1
Sorry, Charlie. Not enough tickets available.
VII. Write a program to perform CRUD operations on the student table in a database using
JDBC.
To perform CRUD (Create, Read, Update, Delete) operations on a `student` table in a database using
JDBC (Java Database Connectivity), you can follow the steps below. This example assumes you
have a database set up with a `student` table.
Prerequisites:
1. JDBC Driver: Ensure you have the JDBC driver for your database (e.g., MySQL, PostgreSQL).
2. Database Setup:
- Create a database (e.g., `school`).
- Create a `student` table with columns like `id`, `name`, `age`, and `grade`.
Below is an example SQL script to create the `student` table:
CREATE DATABASE school;
USE school;
CREATE TABLE student ( id INT PRIMARY
KEY AUTO_INCREMENT, name
VARCHAR(50), age INT, grade
VARCHAR(5)
);
Java Program to Perform CRUD Operations-
import [Link];
import
[Link];
import
[Link];
import [Link];
import [Link];
import [Link];
public class StudentCRUD {
// Database URL, username, and password static final String
DB_URL = "jdbc:mysql://localhost:3306/school"; static final
String USER = "root"; static final String PASS = "password";
// JDBC objects
private Connection conn = null; private
Statement stmt = null; private
PreparedStatement pstmt = null; public
StudentCRUD() {
try {
// 1. Open a connection
conn = [Link](DB_URL, USER,
PASS); } catch (SQLException e) { [Link]();
}
}
// Create a new student record
public void createStudent(String name, int age, String grade) {
String sql = "INSERT INTO student (name, age, grade) VALUES (?, ?, ?)";
try {
pstmt = [Link](sql);
[Link](1, name);
[Link](2, age);
[Link](3, grade);
[Link]();
[Link]("Student created
successfully!"); } catch (SQLException e)
{ [Link](); } finally
{ closePreparedStatement();
}
}
// Read and display student records
public void readStudents() {
String sql = "SELECT * FROM student";
try {
stmt = [Link]();
ResultSet rs =
[Link](sql); while
([Link]()) { int id =
[Link]("id");
String name =
[Link]("name"); int age =
[Link]("age");
String grade = [Link]("grade");
[Link]("ID: " + id + ", Name: " + name +
", Age: " + age + ", Grade: " + grade); }
} catch (SQLException e)
{ [Link](); } finally
{ closeStatement();
}
}
// Update a student record
public void updateStudent(int id, String name, int age, String grade) { String sql
= "UPDATE student SET name = ?, age = ?, grade = ? WHERE id = ?"; try {
pstmt = [Link](sql);
[Link](1, name); [Link](2,
age); [Link](3, grade);
[Link](4, id); int rowsUpdated =
[Link](); if (rowsUpdated
> 0) {
[Link]("Student updated successfully!");
} else {
[Link]("Student with ID " + id + " not found.");
}
} catch (SQLException e) {
[Link](); }
finally
{ closePreparedStatement
();
}
}
// Delete a student record public
void deleteStudent(int id) {
String sql = "DELETE FROM student WHERE id = ?";
try { pstmt =
[Link](sql);
[Link](1, id); int rowsDeleted =
[Link](); if (rowsDeleted
> 0) {
[Link]("Student deleted successfully!");
} else {
[Link]("Student with ID " + id + " not found.");
}
} catch (SQLException e)
{ [Link](); } finally
{ closePreparedStatement();
}
}
// Close PreparedStatement
private void
closePreparedStatement() { try
{ if (pstmt != null)
[Link](); } catch
(SQLException e)
{ [Link]();
}
} // Close Statement private
void closeStatement() { try
{ if (stmt != null) [Link]();
} catch (SQLException e)
{ [Link]();
}
}
// Close Connection public
void closeConnection() { try {
if (conn != null)
[Link](); } catch
(SQLException e)
{ [Link]();
} } public static void main(String[]
args) { StudentCRUD studentCRUD
= new StudentCRUD();
// Create student
[Link]("RAMA", 24, "A");
[Link]("LAKHAN", 22, "B");
// Read students
[Link]("Reading
students...");
[Link]();
// Update student
[Link]("Updating student...");
[Link](1, "RAMA", 22, "A+");
// Delete student
[Link]("Deleting student...");
[Link](2);
// Read students again
[Link]("Reading students after update and delete...");
[Link]();
// Close connection
[Link]();
}
}
Note: Ensure MySQL JDBC Driver: Make sure the MySQL
JDBC driver (`mysql- connector-java` .JAR file) is in
your classpath.
Output:
Student created successfully!
Student created successfully!
Reading students...
ID: 1, Name: RAMA, Age: 24,
Grade: A ID: 2, Name: LAKHAN, Age: 22,
Grade: B Updating student...
Student updated successfully!
Deleting student...
Student deleted successfully!
Reading students after update and delete...
ID: 1, Name: RAMA, Age: 22, Grade: A+
VIII. Develop an applet and swing in Java that displays a simple message
i) An applet is a small Java program that runs in a web browser or an applet viewer. Below example
displays a simple message using applet.
import [Link];
import [Link];
public class SimpleApplet extends Applet {
@Override public void
paint(Graphics g) {
[Link]("Hello World!", 50, 75);
}
}
After compile the above code, write the below code in text editor like notepad and save it as
`[Link]`
<html>
<body>
<applet code="[Link]" width="300" height="150">
</applet>
</body>
</html>
- `paint` Method: The `paint` method is overridden to display a message. The `Graphics` object `g` is
used to draw the string on the applet's window.
- HTML Embed: The applet is embedded in an HTML file using the `<applet>` tag (as shown in the
comment). However, modern browsers no longer support Java applets, so you would typically run
this using an applet viewer.
Running the Applet:
1. Compile the Java file:
javac [Link]
2. Run the applet using an applet viewer:
appletviewer [Link]
Output:
ii) Swing is a GUI toolkit in Java for building standalone applications. Swing is the preferred method
for creating Java GUIs today since applets are largely obsolete due to modern web security
concerns and lack of support in browsers. Below example displays a simple message using Swing.
import [Link]; import
[Link]; import
[Link]; public class
SimpleSwingApp { public static void
createAndShowGUI() {
// Create the frame
JFrame frame = new JFrame("Simple Swing App");
[Link](JFrame.EXIT_ON_CLOSE); // Add a label with a message
JLabel label = new JLabel("Hello, this is a simple Swing application!", [Link]);
[Link](label);
// Set the frame size and make it visible
[Link](400, 200);
[Link](true);
} public static void main(String[]
args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
[Link](() -> createAndShowGUI());
}
}
- `JFrame`: The main window where the components are placed.
- `JLabel`: A label that displays a simple message.
- `[Link]`: Ensures that the GUI creation and updates happen on the Event
Dispatch Thread (EDT), which is the standard practice for thread safety in Swing applications. -
Compile and Run the swing application as like a java program.
Output:
IX. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
Handle any possible exceptions like divided by zero.
1. `JTextField display`:
- The text field displays the current number, result, or error messages.
- It is non-editable, meaning users can only interact with the calculator via buttons.
2. Buttons and `GridLayout`:
- The buttons for digits (`0-9`) and operations (`+`, `-`, `*`, `/`, `C`, `=`) are arranged using a
`GridLayout` with 4 rows and 4 columns.
- The `C` button clears the display and resets the calculator.
3. Action Handling:
- The program checks if the button pressed is a digit or an operator.
- If a digit is pressed, it is appended to the display.
- If an operator is pressed, the current number is stored as the first operand, and the operator is
saved.
- When `=` is pressed, the calculation is performed based on the saved operator.
4. Exception Handling:
- The program handles division by zero by catching an `ArithmeticException` and displaying an
error message.
- A general exception is also caught to handle any other unexpected errors.
5. Main Method:
- The main method uses `[Link]` to ensure that the GUI is created and updated
on the Event Dispatch Thread (EDT).
import [Link].*; import [Link].*; import
[Link]; import [Link]; public
class SimpleCalculator extends JFrame implements ActionListener
{ private JTextField display;
private String currentOperator; private double result, operand;
public
SimpleCalculator() { // Create the display field
display = new JTextField();
[Link](false);
[Link]([Link]
);
// Create the panel to hold buttons JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));
// Add buttons to the panel
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String text : buttons) { JButton
button = new JButton(text);
[Link](this);
[Link](button);
}
// Set the layout of the frame
setLayout(new BorderLayout());
add(display, [Link]);
add(panel, [Link]);
// Frame settings setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
); setLocationRelativeTo(null);
setVisible(true); //
Initialize variables
currentOperator =
""; result = 0;
operand = 0; }
@Override
public void actionPerformed(ActionEvent e)
{ String command = [Link]();
try { if ([Link](0) >= '0' && [Link](0)
<= '9') { [Link]([Link]() + command); } else
if ([Link]("C")) { [Link](""); result = 0;
operand = 0; currentOperator = ""; } else if
([Link]("="))
{ calculate([Link]([Link]()));
[Link]([Link](result)); currentOperator =
""; } else { if (![Link]())
{ calculate([Link]([Link]()));
[Link]([Link](result));
} else { result =
[Link]([Link]());
} currentOperator = command; [Link]("");
}
} catch (ArithmeticException ex)
{ [Link]("Error: Division by zero");
} catch (Exception ex)
{ [Link]("Error");
} } private void calculate(double
input) { switch (currentOperator)
{ case "+": result += input; break;
case "-": result -= input; break; case
"*": result *= input; break;
case "/":
if (input == 0) {
throw new ArithmeticException("Cannot divide by zero");
} result /=
input; break;
}}
public static void main(String[] args) {
[Link](SimpleCalculator::new);
}
}
Output:
X. Write a Java program that handles Keyboard and Mouse events and shows the event name
at the center of the window when an event is fired. [Use Adapter classes]
1. `JFrame` and `JLabel`:
- The program uses a `JFrame` to create the window and a `JLabel` to display the event name at
the center of the window.
2. Adapter Classes:
- To handle keyboard and mouse events in Java, you can use the `KeyAdapter` and
`MouseAdapter` classes.
- `KeyAdapter`: Handles keyboard events (`keyPressed`, `keyReleased`, `keyTyped`).
- `MouseAdapter`: Handles basic mouse events (`mouseClicked`, `mousePressed`,
`mouseReleased`, `mouseEntered`, `mouseExited`).
- `MouseMotionAdapter`: Handles mouse motion events (`mouseMoved`, `mouseDragged`).
3. Event Handling:
- When a key is pressed, released, or typed, the corresponding event name and key information are
displayed in the label.
- When the mouse is clicked, pressed, released, or moved, the event name is updated in the label.
4. setFocusable(true):
- This ensures that the frame can receive keyboard events.
5. Main Method:
- The main method uses `[Link]` to ensure the GUI is created on the Event
Dispatch Thread (EDT).
Java Program to Handling Keyboard and Mouse Events-
import [Link].*;
import [Link].*;
import [Link].*;
public class EventHandlingDemo extends JFrame
{ private JLabel label; public
EventHandlingDemo() {
// Set up the frame setTitle("Event Handling Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
); setLocationRelativeTo(null); setLayout(new
BorderLayout()); // Create a label to display the event
name label = new JLabel("",
[Link]); [Link](new
Font("Arial", [Link], 24)); add(label,
[Link]);
// Add key and mouse listeners using adapter classes
addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) { [Link]("Key
Pressed: " + [Link]([Link]())); }
@Override public void
keyReleased(KeyEvent e) {
[Link]("Key Released: " +
[Link]([Link]())); }
@Override public void keyTyped(KeyEvent e)
{ [Link]("Key Typed: " +
[Link]());
}
});
addMouseListener(new MouseAdapter() {
@Override public void
mouseClicked(MouseEvent e)
{ [Link]("Mouse Clicked");
}
@Override public void
mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e)
{ [Link]("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e)
{ [Link]("Mouse Entered");
}
@Override public void
mouseExited(MouseEvent e)
{ [Link]("Mouse Exited");
} });
addMouseMotionListener(new MouseMotionAdapter() {
@Override public void
mouseMoved(MouseEvent e)
{ [Link]("Mouse Moved");
}
@Override public void
mouseDragged(MouseEvent e)
{ [Link]("Mouse
Dragged");
} }); setFocusable(true); // To
ensure the frame can receive
key events
}
public static void main(String[] args) {
[Link](() - >{
EventHandlingDemo frame = new
EventHandlingDemo();
[Link](true);
});
}
}
Output: