Java LAB Manual
1.Use Eclipse or Net bean 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.
Program:
public class NumberCheck {
public static void main(String[] args) {
int totalEven = 0;
int totalodd = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even");
totalEven++;
} else {
System.out.println(i + " is odd");
totalodd++;
}
}
System.out.println("Total even numbers from 1 to 10: " + totalEven);
System.out.println("Total even numbers from 1 to 10: " + totalodd);
}}
Output:
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.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator extends JFrame implements ActionListener {
JTextField textField;
double num1 = 0, num2 = 0, result = 0;
String operator = "";
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
textField.setEditable(false);
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "C", "=", "%"
};
for (String text : buttons) {
JButton button = new JButton(text);
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
if (input.charAt(0) >= '0' && input.charAt(0) <= '9') {
textField.setText(textField.getText() + input);
} else if (input.equals("C")) {
textField.setText("");
num1 = num2 = result = 0;
operator = "";
} else if (input.equals("=")) {
try {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "%":
if (num2 == 0) throw new ArithmeticException();
result = num1 % num2; break;
}
textField.setText(String.valueOf(result));
} catch (ArithmeticException ex) {
textField.setText("Cannot divide by 0");
}
} else {
try {
num1 = Double.parseDouble(textField.getText());
operator = input;
textField.setText("");
} catch (NumberFormatException ex) {
textField.setText("Invalid Input");
}
}
}
public static void main(String[] args) {
new SimpleCalculator();
}
}
Output:
3.A) Develop an applet in Java that displays a simple message.
Program:
import javax.swing.*;
public class SimpleMessageSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Message");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel messageLabel = new JLabel("Hello, Java Swing!", JLabel.CENTER);
frame.add(messageLabel);
frame.setVisible(true);
}}
Output:
3.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.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FactorialSwingApp extends JFrame implements ActionListener {
JTextField inputField, outputField;
JButton computeBtn;
public FactorialSwingApp() {
setTitle("Factorial Calculator");
setSize(300, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
JLabel inputLabel = new JLabel("Enter Number:");
inputField = new JTextField(10);
JLabel outputLabel = new JLabel("Factorial:");
outputField = new JTextField(15);
outputField.setEditable(false);
computeBtn = new JButton("Compute");
computeBtn.addActionListener(this);
add(inputLabel);
add(inputField);
add(outputLabel);
add(outputField);
add(computeBtn);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int num = Integer.parseInt(inputField.getText());
long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
outputField.setText(String.valueOf(fact));
} catch (NumberFormatException ex) {
outputField.setText("Invalid Input");
}
}
public static void main(String[] args) {
new FactorialSwingApp();
}
}
Output:
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.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DivisionGUI extends JFrame implements ActionListener {
JTextField num1Field, num2Field, resultField;
JButton divideButton;
public DivisionGUI() {
setTitle("Integer Division");
setSize(350, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 10, 10));
// Labels and TextFields
add(new JLabel("Num1:"));
num1Field = new JTextField();
add(num1Field);
add(new JLabel("Num2:"));
num2Field = new JTextField();
add(num2Field);
add(new JLabel("Result:"));
resultField = new JTextField();
resultField.setEditable(false);
add(resultField);
// Button
divideButton = new JButton("Divide");
divideButton.addActionListener(this);
add(divideButton);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(num1Field.getText().trim());
int num2 = Integer.parseInt(num2Field.getText().trim());
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
int result = num1 / num2;
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter valid integers.", "Number
Format Error", JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(this, "Division by zero is not allowed.",
"Arithmetic Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new DivisionGUI();
}
}
Output:
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.
Programs:
import java.util.Random;
class NumberGenerator extends Thread {
public void run() {
Random rand = new Random();
while (true) {
int num = rand.nextInt(100); // Random number between 0–99
System.out.println("\nGenerated Number: " + num);
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
}
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
}
}
class SquareThread extends Thread {
int number;
SquareThread(int num) {
this.number = num;
}
public void run() {
int square = number * number;
System.out.println("Square of " + number + " is: " + square);
}
}
class CubeThread extends Thread {
int number;
CubeThread(int num) {
this.number = num;
}
public void run() {
int cube = number * number * number;
System.out.println("Cube of " + number + " is: " + cube);
}
}
public class MultiThreadExample {
public static void main(String[] args) {
NumberGenerator ng = new NumberGenerator();
ng.start(); // Start the generator thread
}
}
Output:
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.
Program:
import java.util.*;
class Node {
int data;
Node prev, next;
Node(int data) {
this.data = data;
}
}
class DoublyLinkedList {
Node head;
void insert(int data) {
Node newNode = new Node(data);
if (head == null) head = newNode;
else {
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = newNode;
newNode.prev = temp;
}
}
void delete(int val) {
Node temp = head;
while (temp != null && temp.data != val) temp = temp.next;
if (temp == null) {
System.out.println("Element not found.");
return;
}
if (temp == head) head = temp.next;
if (temp.prev != null) temp.prev.next = temp.next;
if (temp.next != null) temp.next.prev = temp.prev;
System.out.println("Deleted: " + val);
}
void display() {
System.out.print("List: ");
for (Node temp = head; temp != null; temp = temp.next)
System.out.print(temp.data + " ");
System.out.println();
}
}
public class DLLDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DoublyLinkedList dll = new DoublyLinkedList();
System.out.print("How many elements? ");
int n = sc.nextInt();
System.out.println("Enter elements:");
while (n-- > 0) dll.insert(sc.nextInt());
dll.display();
System.out.print("Delete element: ");
dll.delete(sc.nextInt());
dll.display();
sc.close();
}
}
Output:
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.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLightSimulator extends JFrame implements ActionListener {
JRadioButton redBtn, yellowBtn, greenBtn;
JLabel messageLabel;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Label (initially empty)
messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 24));
add(messageLabel);
// Radio Buttons
redBtn = new JRadioButton("Red");
yellowBtn = new JRadioButton("Yellow");
greenBtn = new JRadioButton("Green");
// Grouping radio buttons
ButtonGroup group = new ButtonGroup();
group.add(redBtn);
group.add(yellowBtn);
group.add(greenBtn);
// Add Action Listeners
redBtn.addActionListener(this);
yellowBtn.addActionListener(this);
greenBtn.addActionListener(this);
// Add buttons to frame
add(redBtn);
add(yellowBtn);
add(greenBtn);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (redBtn.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowBtn.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.ORANGE);
} else if (greenBtn.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
Output:
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.
Program:
import java.util.Scanner;
abstract class Shape {
int a, b;
abstract void printArea();
}
class Rectangle extends Shape {
Rectangle(int len, int bre) { a = len; this.b = bre; }
void printArea() { System.out.println("Rectangle: " + (a * b)); }
}
class Triangle extends Shape {
Triangle(int base, int height) { a = base; b = height; }
void printArea() { System.out.println("Triangle: " + (0.5 * a * b)); }
}
class Circle extends Shape {
Circle(int r) { a = r; }
void printArea() { System.out.println("Circle: " + (Math.PI * a * a)); }
}
public class ShapeTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Rectangle length bredth: ");
new Rectangle(sc.nextInt(), sc.nextInt()).printArea();
System.out.print("Triangle base height: ");
new Triangle(sc.nextInt(), sc.nextInt()).printArea();
System.out.print("Circle radius: ");
new Circle(sc.nextInt()).printArea();
sc.close();
}
}
Output:
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.
Program:
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class TableDisplay extends JFrame {
public TableDisplay() {
setTitle("Table Viewer");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(0, 3)); // 3 columns (based on Table.txt)
try {
BufferedReader br = new BufferedReader(new FileReader("Table.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(",");
for (String field : fields) {
add(new JLabel(field.trim(), JLabel.CENTER));
}
}
br.close();
} catch (IOException e) {
add(new JLabel("Error: File not found", JLabel.CENTER));
}
setVisible(true);
}
public static void main(String[] args) {
new TableDisplay();
}
}
Output:
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).
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEventsDemo extends JFrame {
String msg = "";
public MouseEventsDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent e) {
msg = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e) {
msg = "Mouse Exited";
repaint();
}
});
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString(msg, getWidth() / 2 - 60, getHeight() / 2);
}
public static void main(String[] args) {
new MouseEventsDemo();
}
}
Output:
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).
Program:
import java.io.*;
import java.util.*;
public class PhoneBookSimple {
public static void main(String[] args) {
HashMap<String, String> phoneBook = new HashMap<>();
try (BufferedReader br = new BufferedReader(new
FileReader("PhoneBook.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\t");
if (parts.length == 2) {
phoneBook.put(parts[0].trim(), parts[1].trim()); // Name → Phone
phoneBook.put(parts[1].trim(), parts[0].trim()); // Phone → Name
}
}
} catch (IOException e) {
System.out.println("File error: " + e);
return;
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name or Phone: ");
String input = sc.nextLine().trim();
if (phoneBook.containsKey(input)) {
System.out.println("Result: " + phoneBook.get(input));
} else {
System.out.println("Record not found.");
}
sc.close();
}
}
Output:
12. Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.
Program:
class Buffer {
int data;
boolean hasData = false;
synchronized void produce(int val) {
while (hasData) {
try { wait(); } catch (Exception e) {}
}
data = val;
System.out.println("Produced: " + data);
hasData = true;
notify();
}
synchronized void consume() {
while (!hasData) {
try { wait(); } catch (Exception e) {}
}
System.out.println("Consumed: " + data);
hasData = false;
notify();
}
}
class Producer extends Thread {
Buffer b;
Producer(Buffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
b.produce(i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
class Consumer extends Thread {
Buffer b;
Consumer(Buffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
b.consume();
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
public class PC {
public static void main(String[] args) {
Buffer b = new Buffer();
new Producer(b).start();
new Consumer(b).start();
}
}
Output:
13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
Program:
import java.io.File;
public class ListFilesRecursively {
public static void main(String[] args) {
File folder = new File("your file path"); // replace with your directory path
if (folder.exists() && folder.isDirectory()) {
listFiles(folder);
} else {
System.out.println("Invalid directory!");
}
}
static void listFiles(File dir) {
File[] files = dir.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isFile()) {
System.out.println("File: " + file.getAbsolutePath());
} else if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
listFiles(file); // Recursive call
}
}
}
}
Output: