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

JAVA Record

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

JAVA Record

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1. Use IntelliJ IDEA platform and acquaint yourself with the various menus.

Create a test project, add a


test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods, and classes. Try debug step by step with a small program
of about 10 to 15 lines which contains at least one if else condition and a for loop.

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:

public static void main(String[] args) {


}
Step 3: Write a Test Program
Add the following code within the main method:

public class TestProgram {


public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is 5 or less");
}

for (int i = 0; i < 5; i++) {


System.out.println("Count: " + i);
}
}
}
Step 4: Use IntelliJ Features
1. Auto Suggestions and Auto Fill: Type System.out.println() and observe IntelliJ’s auto-suggestions,
such as sysout to auto-complete to System.out.println.
2. Code Formatting: Use Code > Reformat Code (or Ctrl + Alt + L on Windows/Linux, Cmd + Option
+ L on macOS) to clean up the code.
3. Refactoring:
o Right-click a variable (e.g., number), choose Refactor > Rename, and enter a new name.
o You can also do this for methods and classes.
Step 5: Run and Debug the Program
1. To run the program, click Run (or press Shift + F10).
2. To debug, set a breakpoint by clicking in the left margin beside a line.
3. Click the Debug button (or press Shift + F9).
4. Use Step Over (F8), Step Into (F7), and Step Out (Shift + F8) to examine the execution step-by-
step.
Output
The program should output the following:
Number is greater than 5
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Result
The test program runs successfully, and IntelliJ features such as auto suggestions, code formatting,
refactoring, and debugging enhance the coding experience. This exercise provides hands-on experience
with IntelliJ IDEA’s development and debugging tools, crucial for learning Java effectively.

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

exceptions like divided by zero.

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.

Step 1: Set Up the Project

1. Open IntelliJ IDEA and create a new Java project.

2. Add a new Java class named Calculator.

Step 2: Import Necessary Packages

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;

Step 3: Define the Calculator Class

Create a class Calculator that extends JFrame and implements ActionListener for handling button clicks.

public class Calculator extends JFrame implements ActionListener {

private JTextField display;

private double num1 = 0, num2 = 0, result = 0;

private char operator;

public Calculator() {

// Set up frame properties

setTitle("Simple Calculator");

setSize(300, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create display field

display = new JTextField();

display.setEditable(false);

display.setFont(new Font("Arial", Font.PLAIN, 24));

add(display, BorderLayout.NORTH);

// Create buttons

String[] buttonLabels = {

"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"0", "C", "=", "+"

};

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 5, 5));

// Add buttons to the panel

for (String label : buttonLabels) {

JButton button = new JButton(label);

button.setFont(new Font("Arial", Font.BOLD, 18));

button.addActionListener(this);

panel.add(button);

add(panel, BorderLayout.CENTER);

setVisible(true);

}
Step 4: Handle Button Clicks

Implement the actionPerformed method to handle button events:

@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

try {

if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {

display.setText(display.getText() + command);

} else if (command.equals("C")) {

display.setText("");

} else if (command.equals("=")) {

num2 = Double.parseDouble(display.getText());

switch (operator) {

case '+': result = num1 + num2; break;

case '-': result = num1 - num2; break;

case '*': result = num1 * num2; break;

case '/':

if (num2 == 0) {

display.setText("Error: Div by 0");

return;

} else {

result = num1 / num2;

break;

display.setText(String.valueOf(result));

num1 = result;

} else {
num1 = Double.parseDouble(display.getText());

operator = command.charAt(0);

display.setText("");

} catch (Exception ex) {

display.setText("Error");

Step 5: Main Method to Run the Program

Add the main method to initialize and display the calculator:

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new Calculator());

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.

3. A) Develop an applet in Java that displays a simple message.


B) Develop an applet in Java that receives an integer in one text field, and computes its factorial

Value and returns it in another text field, when the button named “Compute” is clicked.

3(A): Applet to Display a Simple Message

Aim

To develop a Java applet that displays a simple message on the applet window.

Step 1: Set Up the Applet Class

1. Open your Java IDE, create a new Java file named SimpleMessageApplet.

2. Import the required applet and graphics packages.

Step 2: Define the Applet Class

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleMessageApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Welcome to Java Applet Programming!", 20, 50);

Step 3: HTML to Run the Applet

Create an HTML file to embed the applet:

<!DOCTYPE html>

<html>

<body>

<applet code="SimpleMessageApplet.class" width="300" height="100">

</applet>

</body>

</html>

Output
The applet displays the message "Welcome to Java Applet Programming!" on the applet window.

3(B): Applet to Compute Factorial

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.

Step 1: Set Up the Applet Class

1. Create a new Java file named FactorialApplet.

2. Import the necessary packages for GUI components.

Step 2: Define the Applet Class

import java.applet.Applet;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class FactorialApplet extends Applet implements ActionListener {

TextField inputField, resultField;

Button computeButton;

public void init() {

Label inputLabel = new Label("Enter a number:");

Label resultLabel = new Label("Factorial:");

inputField = new TextField(10);

resultField = new TextField(10);

resultField.setEditable(false);

computeButton = new Button("Compute");

computeButton.addActionListener(this);
add(inputLabel);

add(inputField);

add(resultLabel);

add(resultField);

add(computeButton);

@Override

public void actionPerformed(ActionEvent e) {

try {

int number = Integer.parseInt(inputField.getText());

int factorial = computeFactorial(number);

resultField.setText(String.valueOf(factorial));

} catch (NumberFormatException ex) {

resultField.setText("Invalid input");

private int computeFactorial(int n) {

if (n == 0) return 1;

int fact = 1;

for (int i = 1; i <= n; i++) {

fact *= i;

return fact;

Step 3: HTML to Run the Applet


Create an HTML file to embed the applet:

<!DOCTYPE html>

<html>

<body>

<applet code="FactorialApplet.class" width="400" height="200">

</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.

Display the exception in a message dialog box.

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.

Step 1: Set Up the Project

1. Open your Java IDE and create a new Java file named DivisionApp.

2. Import the necessary Swing and AWT packages.

Step 2: Define the DivisionApp Class

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class DivisionApp extends JFrame implements ActionListener {

private JTextField num1Field, num2Field, resultField;

private JButton divideButton;

public DivisionApp() {

// Set up the frame

setTitle("Integer Division");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(4, 2));

// Create components
JLabel num1Label = new JLabel("Num1:");

JLabel num2Label = new JLabel("Num2:");

JLabel resultLabel = new JLabel("Result:");

num1Field = new JTextField();

num2Field = new JTextField();

resultField = new JTextField();

resultField.setEditable(false); // Result field is not editable

divideButton = new JButton("Divide");

divideButton.addActionListener(this); // Register action listener

// Add components to the frame

add(num1Label);

add(num1Field);

add(num2Label);

add(num2Field);

add(resultLabel);

add(resultField);

add(divideButton);

setVisible(true); // Make the frame visible

@Override

public void actionPerformed(ActionEvent e) {

try {

// Parse input numbers

int num1 = Integer.parseInt(num1Field.getText());


int num2 = Integer.parseInt(num2Field.getText());

// Perform division

if (num2 == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

int result = num1 / num2;

// Display result

resultField.setText(String.valueOf(result));

} catch (NumberFormatException ex) {

// Handle invalid input (non-integer)

JOptionPane.showMessageDialog(this, "Please enter valid integers.", "Input Error",


JOptionPane.ERROR_MESSAGE);

} catch (ArithmeticException ex) {

// Handle division by zero

JOptionPane.showMessageDialog(this, ex.getMessage(), "Arithmetic Error",


JOptionPane.ERROR_MESSAGE);

public static void main(String[] args) {

SwingUtilities.invokeLater(DivisionApp::new);

Explanation of the Code

1. Imports: Import necessary classes from javax.swing for GUI components and java.awt for layout
management.

2. DivisionApp Class: Extends JFrame to create a window.


3. Constructor: Sets up the frame, creates labels, text fields for inputs and results, and the divide
button. The layout is set to a grid for organized placement.

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.

5. Main Method: Launches the GUI on the Event Dispatch Thread.

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.

Step 1: Set Up the Project

1. Open your Java IDE and create a new Java file named MultiThreadApp.

2. Import the necessary packages.

Step 2: Define the MultiThreadApp Class

import java.util.Random;

public class MultiThreadApp {

private static volatile int randomNumber; // Shared variable for threads

public static void main(String[] args) {

Thread numberGenerator = new Thread(new NumberGenerator());

Thread evenSquareCalculator = new Thread(new EvenSquareCalculator());

Thread oddCubeCalculator = new Thread(new OddCubeCalculator());

numberGenerator.start();

evenSquareCalculator.start();

oddCubeCalculator.start();

}
// Thread to generate random integers

static class NumberGenerator implements Runnable {

private Random random = new Random();

@Override

public void run() {

while (true) {

randomNumber = random.nextInt(100); // Generate a random number between 0 and 99

System.out.println("Generated Number: " + randomNumber);

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

break;

// Thread to calculate the square of even numbers

static class EvenSquareCalculator implements Runnable {

@Override

public void run() {

while (true) {

if (randomNumber % 2 == 0) {

int square = randomNumber * randomNumber;

System.out.println("Even Number: " + randomNumber + ", Square: " + square);

try {
Thread.sleep(100); // Sleep to reduce CPU usage

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

break;

// Thread to calculate the cube of odd numbers

static class OddCubeCalculator implements Runnable {

@Override

public void run() {

while (true) {

if (randomNumber % 2 != 0) {

int cube = randomNumber * randomNumber * randomNumber;

System.out.println("Odd Number: " + randomNumber + ", Cube: " + cube);

try {

Thread.sleep(100); // Sleep to reduce CPU usage

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

break;

Explanation of the Code


1. Imports: Import the Random class for generating random numbers.

2. Shared Variable: Declare a volatile integer randomNumber to ensure visibility across threads.

3. Main Method:

o Create and start three threads: NumberGenerator, EvenSquareCalculator, and


OddCubeCalculator.

4. NumberGenerator Class: Implements Runnable to generate a random integer every second:

o Uses a loop to generate random numbers between 0 and 99.

o Sleeps for 1 second after generating a number.

5. EvenSquareCalculator Class: Implements Runnable to calculate the square of even numbers:

o Checks if the randomNumber is even and computes its square.

o Sleeps for 100 milliseconds to prevent busy waiting.

6. OddCubeCalculator Class: Implements Runnable to calculate the cube of odd numbers:

o Checks if the randomNumber is odd and computes its cube.

o Sleeps for 100 milliseconds to prevent busy waiting.

Output

When you run the program, you will see output like this in the console:

Generated Number: 47

Odd Number: 47, Cube: 103823

Generated Number: 22

Even Number: 22, Square: 484

Generated Number: 35

Odd Number: 35, Cube: 42875

...

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:

Create a doubly linked list of elements.

Delete a given element from the above list.

Display the contents of the list after deletion.

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.

Step 1: Define the Node Class

First, create a class Node that represents a single element in the doubly linked list.

class Node {

int data; // Data stored in the node

Node next; // Pointer to the next node

Node prev; // Pointer to the previous node

public Node(int data) {

this.data = data;

this.next = null;

this.prev = null;

Step 2: Define the DoublyLinkedList Class

Next, create the DoublyLinkedList class that contains methods to add, delete, and display elements.

class DoublyLinkedList {

private Node head; // Head of the list

// Method to add an element at the end of the list

public void add(int data) {


Node newNode = new Node(data);

if (head == null) {

head = newNode; // List is empty

return;

Node temp = head;

while (temp.next != null) {

temp = temp.next; // Traverse to the end of the list

temp.next = newNode; // Link new node at the end

newNode.prev = temp; // Set the previous pointer

// Method to delete a given element

public void delete(int key) {

if (head == null) return; // Empty list

Node temp = head;

// Traverse the list to find the node to delete

while (temp != null) {

if (temp.data == key) {

// Node found

if (temp.prev != null) {

temp.prev.next = temp.next; // Bypass the node

} else {

head = temp.next; // Update head if it's the first node


}

if (temp.next != null) {

temp.next.prev = temp.prev; // Link the previous node to next node

System.out.println("Deleted: " + key);

return;

temp = temp.next; // Move to the next node

System.out.println("Element " + key + " not found in the list.");

// Method to display the contents of the list

public void display() {

Node temp = head;

if (temp == null) {

System.out.println("List is empty.");

return;

System.out.print("Doubly Linked List: ");

while (temp != null) {

System.out.print(temp.data + " ");

temp = temp.next; // Move to the next node

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.

public class Main {

public static void main(String[] args) {

DoublyLinkedList list = new DoublyLinkedList();

// Adding elements to the list

list.add(10);

list.add(20);

list.add(30);

list.add(40);

// Display the list

list.display();

// Deleting an element

list.delete(20); // Delete element 20

list.display(); // Display after deletion

list.delete(50); // Attempt to delete a non-existent element

list.display(); // Display after attempting to delete a non-existent element

Explanation of the Code

1. Node Class: Represents each element of the list with data, next, and prev pointers.

2. DoublyLinkedList Class:

o add(int data): Adds a new element to the end of the list.


o delete(int key): Searches for a node with the given key and removes it from the list,
adjusting pointers accordingly.

o display(): Prints all elements in the list from head to tail.

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:

Doubly Linked List: 10 20 30 40

Deleted: 20

Doubly Linked List: 10 30 40

Element 50 not found in the list.

Doubly Linked List: 10 30 40

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.

Step 1: Set Up the Project

1. Open your Java IDE and create a new Java file named TrafficLightSimulator.

2. Import the necessary Swing and AWT packages.

Step 2: Define the TrafficLightSimulator Class

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class TrafficLightSimulator extends JFrame implements ActionListener {

private JLabel messageLabel; // Label to display the message

private JRadioButton redButton; // Radio button for red light

private JRadioButton yellowButton; // Radio button for yellow light

private JRadioButton greenButton; // Radio button for green light

private ButtonGroup buttonGroup; // Group for radio buttons

public TrafficLightSimulator() {

// Set up the frame

setTitle("Traffic Light Simulator");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create components

messageLabel = new JLabel(); // Initially empty

messageLabel.setFont(new Font("Arial", Font.BOLD, 20));

redButton = new JRadioButton("Red");

yellowButton = new JRadioButton("Yellow");

greenButton = new JRadioButton("Green");

// Group the radio buttons

buttonGroup = new ButtonGroup();

buttonGroup.add(redButton);

buttonGroup.add(yellowButton);

buttonGroup.add(greenButton);

// Add action listeners to radio buttons

redButton.addActionListener(this);

yellowButton.addActionListener(this);

greenButton.addActionListener(this);

// Add components to the frame

add(messageLabel);

add(redButton);

add(yellowButton);

add(greenButton);

setVisible(true); // Make the frame visible

}
@Override

public void actionPerformed(ActionEvent e) {

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);

public static void main(String[] args) {

SwingUtilities.invokeLater(TrafficLightSimulator::new);

Explanation of the Code

1. Imports: Import necessary classes from javax.swing for GUI components and java.awt for layout
management and color.

2. TrafficLightSimulator Class: Extends JFrame to create the main application window.

3. Components:

o JLabel: messageLabel displays the message.

o JRadioButtons: redButton, yellowButton, and greenButton allow the user to select a


traffic light color.

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.

o Registers action listeners for the radio buttons to handle selections.

5. ActionPerformed Method: Updates the message label and its color based on the selected radio
button.

6. Main Method: Launches the GUI on the Event Dispatch Thread.

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:

• Selecting Red will show "Stop" in red.

• Selecting Yellow will show "Ready" in yellow.

• Selecting Green will show "Go" in green.

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

print Area () that prints the area of the given shape.

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.

Step 1: Define the Abstract Class Shape

First, create the abstract class Shape that contains two integers (representing dimensions) and an abstract
method printArea().

abstract class Shape {

int dimension1; // First dimension

int dimension2; // Second dimension

// Constructor to initialize dimensions

public Shape(int dimension1, int dimension2) {

this.dimension1 = dimension1;

this.dimension2 = dimension2;

// Abstract method to print area

public abstract void printArea();

Step 2: Define the Rectangle Class

Next, implement the Rectangle class that calculates and prints the area of a rectangle.

class Rectangle extends Shape {

public Rectangle(int width, int height) {

super(width, height); // Call the parent constructor

}
@Override

public void printArea() {

int area = dimension1 * dimension2; // Area = width * height

System.out.println("Area of Rectangle: " + area);

Step 3: Define the Triangle Class

Implement the Triangle class that calculates and prints the area of a triangle.

class Triangle extends Shape {

public Triangle(int base, int height) {

super(base, height); // Call the parent constructor

@Override

public void printArea() {

double area = 0.5 * dimension1 * dimension2; // Area = 0.5 * base * height

System.out.println("Area of Triangle: " + area);

Step 4: Define the Circle Class

Implement the Circle class that calculates and prints the area of a circle.

class Circle extends Shape {

public Circle(int radius) {

super(radius, 0); // Call the parent constructor; second dimension not used

@Override

public void printArea() {


double area = Math.PI * dimension1 * dimension1; // Area = π * radius²

System.out.println("Area of Circle: " + area);

Step 5: Create the Main Class

Finally, create a Main class with a main method to demonstrate the functionality.

public class Main {

public static void main(String[] args) {

Shape rectangle = new Rectangle(5, 10);

rectangle.printArea(); // Display area of rectangle

Shape triangle = new Triangle(5, 10);

triangle.printArea(); // Display area of triangle

Shape circle = new Circle(7);

circle.printArea(); // Display area of circle

Explanation of the Code

1. Shape Class:

o An abstract class containing two integer dimensions and an abstract method printArea().

o The constructor initializes the dimensions.

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

Area of Triangle: 25.0

Area of Circle: 153.93804002589985

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.

Step 1: Create the Table.txt File

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

Step 2: Define the Java Program

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;

public class TableDisplay extends JFrame {

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);

pack(); // Adjust frame size based on components

setLocationRelativeTo(null); // Center the frame on the screen

setVisible(true);

private void readTableFromFile(String filePath) {

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {

String headerLine = br.readLine(); // Read header

if (headerLine != null) {

String[] headers = headerLine.split(","); // Split by comma

for (String header : headers) {

add(new JLabel(header)); // Add header labels

String rowLine;

while ((rowLine = br.readLine()) != null) {

String[] rowData = rowLine.split(","); // Split by comma

for (String data : rowData) {

add(new JLabel(data)); // Add data labels

} catch (IOException e) {

e.printStackTrace();

}
}

public static void main(String[] args) {

SwingUtilities.invokeLater(TableDisplay::new);

Explanation of the Code

1. Imports: Import necessary classes from javax.swing and java.awt for GUI components and layouts,
and java.io for file reading.

2. TableDisplay Class: Extends JFrame to create the main window.

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 Uses BufferedReader to read the file line by line.

o The first line is read as the header, and labels for each header are created and added to
the frame.

o Subsequent lines are processed similarly to display the data.

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:

| Name | Age | Occupation |

| 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

window when a mouse event is fired (Use Adapter classes).


Aim

To create a Java program that detects various mouse events and displays the event name in the center of
the window.

Step 1: Define the Java Program

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 class MouseEventDemo extends JFrame {

private JLabel eventLabel; // Label to display the event name

public MouseEventDemo() {

setTitle("Mouse Event Demo");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null); // Center the window on the screen

eventLabel = new JLabel("", SwingConstants.CENTER);

eventLabel.setFont(new Font("Arial", Font.BOLD, 24)); // Set font size and style

add(eventLabel); // Add label to the frame

addMouseListener(new MouseAdapter() { // Mouse listener using MouseAdapter

@Override

public void mouseClicked(MouseEvent e) {

eventLabel.setText("Mouse Clicked");

}
@Override

public void mousePressed(MouseEvent e) {

eventLabel.setText("Mouse Pressed");

@Override

public void mouseReleased(MouseEvent e) {

eventLabel.setText("Mouse Released");

@Override

public void mouseEntered(MouseEvent e) {

eventLabel.setText("Mouse Entered");

@Override

public void mouseExited(MouseEvent e) {

eventLabel.setText("Mouse Exited");

});

setVisible(true); // Make the frame visible

public static void main(String[] args) {

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.

2. MouseEventDemo Class: Extends JFrame to create the main application window.

o Constructor:

▪ Sets up the frame title, size, and close operation.

▪ Creates a JLabel to display the event name, centering it in the window.

▪ Adds a MouseAdapter to listen for mouse events. The adapter methods are
overridden to handle the following mouse events:

▪ mouseClicked(): Triggered when the mouse button is clicked.

▪ mousePressed(): Triggered when the mouse button is pressed.

▪ mouseReleased(): Triggered when the mouse button is released.

▪ mouseEntered(): Triggered when the mouse pointer enters the window.

▪ mouseExited(): Triggered when the mouse pointer exits the window.

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.

Step 1: Create the Data File

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

Make sure the fields are separated by tabs (\t).

Step 2: Define the Java Program

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;

public class ContactManager {

private HashMap<String, String> contacts; // HashMap to store name and phone number pairs

public ContactManager(String filePath) {

contacts = new HashMap<>(); // Initialize the HashMap

loadContacts(filePath); // Load contacts from the file

private void loadContacts(String filePath) {


try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {

String line;

while ((line = br.readLine()) != null) {

String[] fields = line.split("\t"); // Split line by tab

if (fields.length == 2) {

String name = fields[0].trim();

String phoneNumber = fields[1].trim();

contacts.put(name, phoneNumber); // Store name and phone number in HashMap

contacts.put(phoneNumber, name); // Store phone number and name in HashMap

} catch (IOException e) {

e.printStackTrace();

public String getContactInfo(String query) {

return contacts.get(query); // Return corresponding value for the query

public static void main(String[] args) {

ContactManager contactManager = new ContactManager("contacts.txt"); // Initialize with file path

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a name or phone number to search:");

String query = scanner.nextLine().trim();

String result = contactManager.getContactInfo(query);

if (result != null) {
System.out.println("Corresponding value: " + result);

} else {

System.out.println("No contact found for: " + query);

scanner.close();

Explanation of the Code

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):

▪ Uses a BufferedReader to read the file line by line.

▪ 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:

o Initializes the ContactManager with the specified file path.

o Prompts the user to enter a name or phone number.

o Retrieves and prints the corresponding value from the HashMap.

Output

When you run the program, it will prompt you to enter a name or phone number. For example:

Enter a name or phone number to search:


Alice

Corresponding value: 1234567890

Or:

Enter a name or phone number to search:

1234567890

Corresponding value: Alice

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

concept of inter thread communication.

Aim
To demonstrate the producer-consumer problem using inter-thread communication with the help of wait()
and notify().

Step 1: Define the Shared Resource

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.

Step 2: Define the Producer and Consumer Classes

We will define two classes: Producer and Consumer, both of which implement Runnable.

Step 3: Implement the Main Class

The main class will set up the shared buffer and start both producer and consumer threads.

Complete Code Example

Here's the complete code for the producer-consumer problem:

import java.util.LinkedList;

import java.util.Queue;

class SharedBuffer {

private Queue<Integer> buffer;

private int capacity;

public SharedBuffer(int capacity) {

this.capacity = capacity;

this.buffer = new LinkedList<>();

// Producer method to add items to the buffer

public synchronized void produce(int item) throws InterruptedException {

while (buffer.size() == capacity) {

System.out.println("Buffer is full. Producer is waiting...");

wait(); // Wait until there's space in the buffer


}

buffer.add(item);

System.out.println("Produced: " + item);

notify(); // Notify the consumer that an item has been produced

// Consumer method to remove items from the buffer

public synchronized int consume() throws InterruptedException {

while (buffer.isEmpty()) {

System.out.println("Buffer is empty. Consumer is waiting...");

wait(); // Wait until there's something to consume

int item = buffer.poll();

System.out.println("Consumed: " + item);

notify(); // Notify the producer that an item has been consumed

return item;

class Producer implements Runnable {

private SharedBuffer sharedBuffer;

public Producer(SharedBuffer sharedBuffer) {

this.sharedBuffer = sharedBuffer;

@Override

public void run() {

for (int i = 1; i <= 10; i++) { // Produce 10 items


try {

sharedBuffer.produce(i);

Thread.sleep(500); // Sleep for a while to simulate production time

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

class Consumer implements Runnable {

private SharedBuffer sharedBuffer;

public Consumer(SharedBuffer sharedBuffer) {

this.sharedBuffer = sharedBuffer;

@Override

public void run() {

for (int i = 1; i <= 10; i++) { // Consume 10 items

try {

sharedBuffer.consume();

Thread.sleep(1000); // Sleep for a while to simulate consumption time

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}
public class ProducerConsumerDemo {

public static void main(String[] args) {

SharedBuffer sharedBuffer = new SharedBuffer(5); // Buffer capacity of 5

Thread producerThread = new Thread(new Producer(sharedBuffer));

Thread consumerThread = new Thread(new Consumer(sharedBuffer));

producerThread.start();

consumerThread.start();

Explanation of the Code

1. SharedBuffer Class:

o Implements the shared buffer with a capacity limit.

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.

o Utilizes wait() and notify() for inter-thread communication:

▪ 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 Implements Runnable and produces integers from 1 to 10.

o Calls the produce() method of the shared buffer and sleeps for 500 milliseconds between
productions.

3. Consumer Class:

o Implements Runnable and consumes items.

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

...

Buffer is full. Producer is waiting...

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

To list all files in a specified directory and its subdirectories.

Step 1: Define the Java Program

Create a new Java file named ListFilesInDirectory.java and implement the following code:

import java.io.File;

public class ListFilesInDirectory {


public static void main(String[] args) {

// Specify the directory path here

String directoryPath = "C:\\path\\to\\your\\directory"; // Change this to your directory path

File directory = new File(directoryPath);

if (directory.exists() && directory.isDirectory()) {

System.out.println("Files in directory: " + directoryPath);

listFiles(directory); // Call the method to list files

} else {

System.out.println("The specified path is not a valid directory.");

// Method to list all files in a directory and its subdirectories

public static void listFiles(File directory) {

File[] files = directory.listFiles(); // Get all files and directories in the current directory

if (files != null) {

for (File file : files) {

if (file.isDirectory()) {

// If the file is a directory, recurse into it

listFiles(file);

} else {

// If it's a file, print its name

System.out.println(file.getAbsolutePath());

}
}

Explanation of the Code

1. Imports: Import the java.io.File class to handle file operations.

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.

o If valid, call the listFiles() method to start listing the files.

3. listFiles(File directory):

o This method takes a File object representing a directory.

o It uses listFiles() to get an array of File objects representing the contents of the directory.

o It iterates through the array:

▪ If a File object is a directory, it calls itself recursively to list files within that
directory.

▪ If it is a file, it prints the absolute path of the file.

Output

When you run the program, it will output the paths of all files found within the specified directory and its
subdirectories. For example:

Files in directory: C:\path\to\your\directory

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.

You might also like