JAVA Record
JAVA Record
Aim
To create a basic Java project in IntelliJ IDEA, explore features like auto suggestions, auto fill, code
formatting, refactoring, and debugging using a simple program with an if-else condition and a for loop.
Step 1: Set Up the Project
1. Open IntelliJ IDEA and click on New Project.
2. Select Java as the project type and configure the Project SDK if not already set.
3. Click Next and then Finish to create the project.
Step 2: Create a Test Class
1. In the Project view, right-click on the src folder.
2. Choose New > Java Class and name it TestProgram.
3. Inside TestProgram, add the main method:
2. 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
Aim
To develop a simple calculator in Java with a graphical user interface (GUI) using Swing components, such
as buttons and a text field, arranged in a grid layout. The calculator should handle basic operations (+, -, *,
/, %) and display the result. It should also handle exceptions like division by zero.
Add the following imports at the beginning of your class to enable Swing and event handling:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Create a class Calculator that extends JFrame and implements ActionListener for handling button clicks.
public Calculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create display field
display.setEditable(false);
add(display, BorderLayout.NORTH);
// Create buttons
String[] buttonLabels = {
};
button.addActionListener(this);
panel.add(button);
add(panel, BorderLayout.CENTER);
setVisible(true);
}
Step 4: Handle Button Clicks
@Override
try {
display.setText(display.getText() + command);
} else if (command.equals("C")) {
display.setText("");
} else if (command.equals("=")) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case '/':
if (num2 == 0) {
return;
} else {
break;
display.setText(String.valueOf(result));
num1 = result;
} else {
num1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
display.setText("");
display.setText("Error");
Output
The calculator window displays a grid of buttons with digits, operators, and a text field for the result. The
calculator performs basic arithmetic operations and shows an error message when dividing by zero or
handling invalid input.
Value and returns it in another text field, when the button named “Compute” is clicked.
Aim
To develop a Java applet that displays a simple message on the applet window.
1. Open your Java IDE, create a new Java file named SimpleMessageApplet.
import java.applet.Applet;
import java.awt.Graphics;
<!DOCTYPE html>
<html>
<body>
</applet>
</body>
</html>
Output
The applet displays the message "Welcome to Java Applet Programming!" on the applet window.
Aim
To develop a Java applet that accepts an integer input, computes its factorial, and displays the result in
another text field upon clicking a "Compute" button.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Button computeButton;
resultField.setEditable(false);
computeButton.addActionListener(this);
add(inputLabel);
add(inputField);
add(resultLabel);
add(resultField);
add(computeButton);
@Override
try {
resultField.setText(String.valueOf(factorial));
resultField.setText("Invalid input");
if (n == 0) return 1;
int fact = 1;
fact *= i;
return fact;
<!DOCTYPE html>
<html>
<body>
</applet>
</body>
</html>
Output
1. The applet displays two text fields and a button labeled "Compute".
2. When an integer is entered in the first field, clicking "Compute" calculates and displays the
factorial in the second text field.
3. If invalid input is entered, the applet displays "Invalid input" in the result field.
Result
• 3(A): The SimpleMessageApplet displays a welcome message, demonstrating basic text output in
an applet.
• 3(B): The FactorialApplet takes an integer input, computes the factorial, and handles invalid
inputs, showing interactive features and error handling in applets.
4. Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw
a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception.
Aim
To create a Java application with a graphical user interface (GUI) that performs integer division, handling
invalid inputs and division by zero exceptions with appropriate error messages displayed in dialog boxes.
1. Open your Java IDE and create a new Java file named DivisionApp.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public DivisionApp() {
setTitle("Integer Division");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create components
JLabel num1Label = new JLabel("Num1:");
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(resultLabel);
add(resultField);
add(divideButton);
@Override
try {
// Perform division
if (num2 == 0) {
// Display result
resultField.setText(String.valueOf(result));
SwingUtilities.invokeLater(DivisionApp::new);
1. Imports: Import necessary classes from javax.swing for GUI components and java.awt for layout
management.
4. Action Listener: Implements actionPerformed to handle button clicks. It parses inputs, checks for
division by zero, and updates the result field. If exceptions occur, a message dialog displays the
error.
Output
• The GUI consists of two input fields (Num1 and Num2), a Result field, and a Divide button.
• When valid integers are input, clicking the Divide button displays the result.
• If non-integer values are entered, a message dialog box shows an input error.
• If Num2 is zero, a message dialog box indicates that division by zero is not allowed.
Result
This Java application provides a user-friendly interface for performing integer division, effectively handling
exceptions and displaying error messages as needed. It demonstrates the use of Swing components and
exception handling in Java GUI programming.
5. Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer every 1 second and if the value is even, the second thread computes the
square of the number and prints. If the value is odd, the third thread will print the value of the cube of
the number.
Aim
To create a Java application that utilizes multiple threads, where the first thread generates a random
integer every second, the second thread computes the square of the number if it's even, and the third
thread computes the cube if the number is odd.
1. Open your Java IDE and create a new Java file named MultiThreadApp.
import java.util.Random;
numberGenerator.start();
evenSquareCalculator.start();
oddCubeCalculator.start();
}
// Thread to generate random integers
@Override
while (true) {
try {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
@Override
while (true) {
if (randomNumber % 2 == 0) {
try {
Thread.sleep(100); // Sleep to reduce CPU usage
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
@Override
while (true) {
if (randomNumber % 2 != 0) {
try {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
2. Shared Variable: Declare a volatile integer randomNumber to ensure visibility across threads.
3. Main Method:
Output
When you run the program, you will see output like this in the console:
Generated Number: 47
Generated Number: 22
Generated Number: 35
...
Result
This Java program demonstrates the use of multithreading to generate random integers and compute their
squares and cubes based on their parity. The use of volatile ensures that threads see the most recent value
of randomNumber, and the application effectively handles concurrent operations in a simple manner.
6. Write a Java program for the following:
Aim
To create a Java program that implements a doubly linked list, providing functionalities to delete a specified
element and display the remaining elements in the list.
First, create a class Node that represents a single element in the doubly linked list.
class Node {
this.data = data;
this.next = null;
this.prev = null;
Next, create the DoublyLinkedList class that contains methods to add, delete, and display elements.
class DoublyLinkedList {
if (head == null) {
return;
if (temp.data == key) {
// Node found
if (temp.prev != null) {
} else {
if (temp.next != null) {
return;
if (temp == null) {
System.out.println("List is empty.");
return;
System.out.println();
}
Step 3: Create the Main Class
Finally, create a Main class with a main method to demonstrate the functionalities of the doubly linked
list.
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.display();
// Deleting an element
1. Node Class: Represents each element of the list with data, next, and prev pointers.
2. DoublyLinkedList Class:
3. Main Class: Demonstrates how to use the doubly linked list by adding elements, deleting a specific
element, and displaying the list contents.
Output
When you run the program, the output will look like this:
Deleted: 20
Result
This Java program successfully implements a doubly linked list, allowing for element addition, deletion,
and display of contents, demonstrating essential linked list operations.
7. Write a Java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with
“Stop” or “Ready” or “Go” should appear above the buttons in the selected color. Initially, there is no
message shown.
Aim
To create a Java program that simulates a traffic light using radio buttons, displaying corresponding
messages based on the selected color.
1. Open your Java IDE and create a new Java file named TrafficLightSimulator.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public TrafficLightSimulator() {
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create components
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
add(messageLabel);
add(redButton);
add(yellowButton);
add(greenButton);
}
@Override
if (redButton.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowButton.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
} else if (greenButton.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
SwingUtilities.invokeLater(TrafficLightSimulator::new);
1. Imports: Import necessary classes from javax.swing for GUI components and java.awt for layout
management and color.
3. Components:
o ButtonGroup: Groups the radio buttons so that only one can be selected at a time.
4. Constructor:
o Sets up the frame, initializes components, and adds them to the frame.
5. ActionPerformed Method: Updates the message label and its color based on the selected radio
button.
Output
When you run the program, it will display a window with radio buttons for red, yellow, and green lights.
Upon selecting a button, the message will appear above the buttons in the corresponding color:
Result
This Java program effectively simulates a traffic light using a GUI, demonstrating the use of radio buttons
and action events to interactively display messages based on user selection.
8. Write a Java program to create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such
that each one of the classes extends the class Shape. Each one of the classes contains only the method
Aim
To create an abstract class Shape with a method to print the area, and three derived classes (Rectangle,
Triangle, Circle) that implement the area calculation for their respective shapes.
First, create the abstract class Shape that contains two integers (representing dimensions) and an abstract
method printArea().
this.dimension1 = dimension1;
this.dimension2 = dimension2;
Next, implement the Rectangle class that calculates and prints the area of a rectangle.
}
@Override
Implement the Triangle class that calculates and prints the area of a triangle.
@Override
Implement the Circle class that calculates and prints the area of a circle.
super(radius, 0); // Call the parent constructor; second dimension not used
@Override
Finally, create a Main class with a main method to demonstrate the functionality.
1. Shape Class:
o An abstract class containing two integer dimensions and an abstract method printArea().
2. Rectangle Class:
o Extends Shape and implements the printArea() method to calculate the area of a
rectangle.
3. Triangle Class:
o Extends Shape and implements the printArea() method to calculate the area of a triangle.
4. Circle Class:
o Extends Shape and implements the printArea() method to calculate the area of a circle.
The second dimension is not used.
5. Main Class:
o Creates instances of Rectangle, Triangle, and Circle, and calls their printArea() methods to
display the respective areas.
Output
When you run the program, you will see output like this:
Area of Rectangle: 50
Result
This Java program successfully implements an abstract class and three derived classes that compute and
display the area of different shapes, demonstrating key concepts of abstraction and inheritance in object-
oriented programming.
9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and
the remaining lines correspond to rows in the table. The elements are separated by commas.
Write a java program to display the table using Labels in Grid Layout.
Aim
To read a comma-separated values (CSV) file and display its contents in a graphical user interface (GUI)
using Swing components arranged in a grid layout.
First, ensure you have a Table.txt file with the following content (as an example):
Name,Age,Occupation
Alice,30,Engineer
Bob,25,Designer
Charlie,35,Manager
Create a new Java file named TableDisplay.java and implement the following code:
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
private static final String FILE_PATH = "Table.txt"; // Path to the text file
public TableDisplay() {
setTitle("Table Display");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(0, 3)); // Change the number of columns based on the header
// Read and display the table from the file
readTableFromFile(FILE_PATH);
setVisible(true);
if (headerLine != null) {
String rowLine;
} catch (IOException e) {
e.printStackTrace();
}
}
SwingUtilities.invokeLater(TableDisplay::new);
1. Imports: Import necessary classes from javax.swing and java.awt for GUI components and layouts,
and java.io for file reading.
o Constructor: Sets up the frame title, layout, and calls the method to read and display the
table.
o GridLayout: Configured to have as many rows as needed (0 allows for automatic row
count) and 3 columns (this can be adjusted based on the number of columns in your
table).
3. readTableFromFile(String filePath):
o The first line is read as the header, and labels for each header are created and added to
the frame.
4. Main Method: Launches the GUI on the Event Dispatch Thread using SwingUtilities.invokeLater.
Output
When you run the program, it will create a window displaying the contents of Table.txt in a grid layout:
| Alice | 30 | Engineer |
| Bob | 25 | Designer |
| Charlie | 35 | Manager |
Result
This Java program reads a table from a text file and displays it in a structured format using JLabels in a grid
layout, demonstrating the use of file I/O and GUI programming in Java.
10. Write a Java program that handles all mouse events and shows the event name at the center of the
To create a Java program that detects various mouse events and displays the event name in the center of
the window.
Create a new Java file named MouseEventDemo.java and implement the following code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public MouseEventDemo() {
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
eventLabel.setText("Mouse Clicked");
}
@Override
eventLabel.setText("Mouse Pressed");
@Override
eventLabel.setText("Mouse Released");
@Override
eventLabel.setText("Mouse Entered");
@Override
eventLabel.setText("Mouse Exited");
});
SwingUtilities.invokeLater(MouseEventDemo::new);
}
Explanation of the Code
1. Imports: Import necessary classes from javax.swing for GUI components and java.awt.event for
handling mouse events.
o Constructor:
▪ Adds a MouseAdapter to listen for mouse events. The adapter methods are
overridden to handle the following mouse events:
o Each overridden method updates the text of eventLabel to show the corresponding event
name.
3. Main Method: Launches the GUI on the Event Dispatch Thread using SwingUtilities.invokeLater.
Output
When you run the program, a window will appear. As you perform mouse actions such as clicking, pressing,
or moving into/out of the window, the label will update to display the name of the mouse event that
occurred at the center of the window.
Result
This Java program effectively handles various mouse events using adapter classes and displays the event
name in a user-friendly GUI, demonstrating the use of event handling in Java Swing.
11. Write a Java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t). It takes a
name or phone number as input and prints the corresponding other value from the hash table (hint:
use hash tables).
Aim
To read records from a text file containing names and phone numbers, store the data in a hash table, and
allow users to query the hash table by either name or phone number.
First, create a text file named contacts.txt with the following content (as an example):
Alice 1234567890
Bob 2345678901
Charlie 3456789012
David 4567890123
Eve 5678901234
Create a new Java file named ContactManager.java and implement the following code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
private HashMap<String, String> contacts; // HashMap to store name and phone number pairs
String line;
if (fields.length == 2) {
} catch (IOException e) {
e.printStackTrace();
if (result != null) {
System.out.println("Corresponding value: " + result);
} else {
scanner.close();
1. Imports: Import necessary classes from java.io for file handling, java.util for data structures, and
java.util.Scanner for user input.
2. ContactManager Class:
o HashMap: contacts to store the mapping between names and phone numbers.
o Constructor: Takes the file path as an argument, initializes the HashMap, and calls the
method to load contacts from the file.
o loadContacts(String filePath):
▪ Each line is split using a tab delimiter to separate name and phone number.
▪ Both name-phone and phone-name pairs are stored in the HashMap for easy
retrieval.
3. getContactInfo(String query): Takes a query (either name or phone number) and returns the
corresponding value from the HashMap.
4. Main Method:
Output
When you run the program, it will prompt you to enter a name or phone number. For example:
Or:
1234567890
Result
This Java program effectively reads a list of contacts from a text file into a hash table and allows for quick
retrieval of information based on user input, demonstrating the use of file I/O and hash tables in Java.
12. Write a Java program that correctly implements the producer – consumer problem using the
Aim
To demonstrate the producer-consumer problem using inter-thread communication with the help of wait()
and notify().
We'll create a shared buffer using a list to hold produced items. The producer will add items to this buffer,
and the consumer will remove them.
We will define two classes: Producer and Consumer, both of which implement Runnable.
The main class will set up the shared buffer and start both producer and consumer threads.
import java.util.LinkedList;
import java.util.Queue;
class SharedBuffer {
this.capacity = capacity;
buffer.add(item);
while (buffer.isEmpty()) {
return item;
this.sharedBuffer = sharedBuffer;
@Override
sharedBuffer.produce(i);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
this.sharedBuffer = sharedBuffer;
@Override
try {
sharedBuffer.consume();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
public class ProducerConsumerDemo {
producerThread.start();
consumerThread.start();
1. SharedBuffer Class:
o Contains methods produce(int item) and consume() for the producer and consumer to
add and remove items, respectively.
o Uses synchronized to ensure that only one thread can access these methods at a time.
▪ wait(): The thread waits until it's notified that it can proceed.
▪ notify(): Notifies a waiting thread that an item has been added or removed.
2. Producer Class:
o Calls the produce() method of the shared buffer and sleeps for 500 milliseconds between
productions.
3. Consumer Class:
o Calls the consume() method of the shared buffer and sleeps for 1000 milliseconds
between consumptions.
4. ProducerConsumerDemo Class:
o The main class initializes the shared buffer and starts the producer and consumer threads.
Output
When you run the program, you will see output similar to the following, showing the interleaving of
production and consumption:
Produced: 1
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
...
Consumed: 3
Produced: 5
...
Result
This Java program successfully implements the producer-consumer problem using inter-thread
communication, demonstrating synchronization with wait() and notify(). It handles the scenario where the
producer waits when the buffer is full and the consumer waits when the buffer is empty.
13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
Aim
Create a new Java file named ListFilesInDirectory.java and implement the following code:
import java.io.File;
} else {
File[] files = directory.listFiles(); // Get all files and directories in the current directory
if (files != null) {
if (file.isDirectory()) {
listFiles(file);
} else {
System.out.println(file.getAbsolutePath());
}
}
2. Main Method:
o Specify the directory path you want to search. Make sure to change the path to point to a
valid directory on your system.
o Create a File object for the directory and check if it exists and is indeed a directory.
3. listFiles(File directory):
o It uses listFiles() to get an array of File objects representing the contents of the directory.
▪ If a File object is a directory, it calls itself recursively to list files within that
directory.
Output
When you run the program, it will output the paths of all files found within the specified directory and its
subdirectories. For example:
C:\path\to\your\directory\file1.txt
C:\path\to\your\directory\subdirectory1\file2.txt
C:\path\to\your\directory\subdirectory1\subdirectory2\file3.txt
Result
This Java program successfully lists all files in a specified directory, including those in subdirectories,
demonstrating recursive directory traversal using the java.io.File class.