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.
Step 1: Install and Open Eclipse/NetBeans
If not installed, download and install Eclipse or NetBeans from their official websites.
Open the IDE and explore menus like File, Edit, Source, Refactor, Run, Debug, Window.
Step 2: Create a Test Project
1.
Eclipse:
2.
1. Click File → New → Java Project
2. Name it TestProject → Click Finish
3. Right-click the src folder → New → Class
4. Name it TestClass and check public static void main(String[] args)
3.
NetBeans:
4.
1. Click File → New Project
2. Select Java Application → Click Next
3. Name it TestProject and Finish
4. Expand the Source Packages → Right-click testproject package → New → Java Class
5. Name it TestClass.java
Step 3: Write a Simple Java Program
TestClass.java file:
public class TestClass {
public static void main(String[] args) {
int num = 10;
if (num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
Step 4: Use Auto-Suggestions and Auto-Fill
Type sysout and press Ctrl + Space (Eclipse) or sout + Tab (NetBeans) → It expands to
System.out.println();
Type for and press Ctrl + Space → Auto-generates a for-loop.
Hover over any syntax error to see quick-fix suggestions.
Step 5: Code Formatting and Refactoring
Format Code:
o Eclipse: Press Ctrl + Shift + F
o NetBeans: Press Alt + Shift + F
Rename a Variable/Method/Class:
o Right-click a variable/method/class → Refactor → Rename
o OR use shortcut Alt + Shift + R (Eclipse)
Step 6: Debugging Step-by-Step
1. Set Breakpoints: Click on the left margin next to a line (where you want to pause execution).
2. Run in Debug Mode: Click Run → Debug As → Java Application OR Press F11.
3. Step Through Code:
1. F5 (Step Into)
2. F6 (Step Over)
3. F7 (Step Return)
4. F8 (Resume)
4. Watch Variables, Breakpoints, Console Output windows to observe execution.
Step 7: Run the Program
Click Run → Run As → Java Application OR press Ctrl + F11.
Check the console output.
2. Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance, Polymorphism and Abstraction]
· Encapsulation: Using private variables with getter/setter methods.
· Inheritance: A subclass inheriting properties and behaviors from a superclass.
· Polymorphism: Method Overriding and Method Overloading.
· Abstraction: Using an abstract class with abstract and concrete methods.
// Abstraction: Abstract class with abstract and concrete methods
abstract class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public abstract void startEngine(); // Abstract method
public void displayBrand() { // Concrete method
System.out.println("Brand: " + brand);
}
}
// Inheritance: Car extends Vehicle
class Car extends Vehicle {
private int speed; // Encapsulation: Private variable
public Car(String brand, int speed) {
super(brand); // Calling superclass constructor
this.speed = speed;
}
// Encapsulation: Getter and Setter
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
// Polymorphism: Overriding startEngine method
@Override
public void startEngine() {
System.out.println("Car engine starting...");
}
// Polymorphism: Method Overloading
public void accelerate() {
speed += 10;
System.out.println("Car accelerated. New speed: " + speed);
}
public void accelerate(int increase) {
speed += increase;
System.out.println("Car accelerated by " + increase + " km/h. New speed: " + speed);
}
}
// Main class to test the program
public class OOPDemo {
public static void main(String[] args) {
// Creating an object of Car class
Car myCar = new Car("Toyota", 50);
// Using Abstraction & Inheritance
myCar.displayBrand();
myCar.startEngine();
// Using Encapsulation
System.out.println("Current Speed: " + myCar.getSpeed());
myCar.setSpeed(60);
System.out.println("Updated Speed: " + myCar.getSpeed());
// Using Polymorphism (Method Overriding & Overloading)
myCar.accelerate();
myCar.accelerate(20);
}
}
· Encapsulation:
The speed variable is private, and we access it through getter/setter methods.
· Inheritance:
Car extends Vehicle, inheriting the brand attribute and displayBrand() method.
· Polymorphism:
Method Overriding: Car provides its own implementation of startEngine().
Method Overloading: accelerate() has two versions – one with no parameters and one with an integer
parameter.
· Abstraction:
Vehicle is an abstract class that has an abstract method startEngine() and a concrete method
displayBrand().
Car provides an implementation for startEngine().
OUTPUT:
Brand: Toyota Car engine starting...
Current Speed: 50
Updated Speed: 60 Car accelerated.
New speed: 70 Car accelerated by 20 km/h.
New speed: 90
3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the usage of custom exceptions in real time
scenario.
· Checked Exception Handling (Using try-catch for IOException)
· Unchecked Exception Handling (Handling ArithmeticException)
· Custom Exception (Creating a LowBalanceException for a banking scenario
import java.io.*;
// Custom Exception for a real-time banking scenario
class LowBalanceException extends Exception {
public LowBalanceException(String message) {
super(message);
}
}
public class ExceptionHandlingDemo {
public static void main(String[] args) {
// Handling Checked Exception
readFile("sample.txt");
// Handling Unchecked Exception
handleArithmeticException();
// Using Custom Exception in a banking scenario
try {
withdrawAmount(5000, 10000); // This will throw LowBalanceException
} catch (LowBalanceException e) {
System.out.println("Exception: " + e.getMessage());
}
}
// Checked Exception: Handling IOException
public static void readFile(String fileName) {
try {
FileReader file = new FileReader(fileName);
BufferedReader br = new BufferedReader(file);
System.out.println("File opened successfully.");
br.close();
} catch (IOException e) {
System.out.println("Checked Exception: File not found or unable to read.");
}
}
// Unchecked Exception: Handling ArithmeticException
public static void handleArithmeticException() {
try {
int result = 10 / 0; // This will cause ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Unchecked Exception: Division by zero is not allowed.");
}
}
// Custom Exception Usage: Banking Scenario
public static void withdrawAmount(double balance, double withdrawAmount)
throws LowBalanceException {
if (withdrawAmount > balance) {
throw new LowBalanceException("Insufficient balance! Available: " + balance
+ ", Requested: " + withdrawAmount);
} else {
System.out.println("Withdrawal successful. Remaining Balance: " + (balance -
withdrawAmount));
}
}
}
OUTPUT:
Checked Exception: File not found or unable to read.
Unchecked Exception: Division by zero is not allowed.
Exception: Insufficient balance! Available: 5000.0, Requested: 10000.0
4. Write a Java program on Random Access File class to perform different read and write operations.
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
String fileName = "sample.txt";
try {
// Create a RandomAccessFile in "rw" mode (read-write)
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
// Writing data to the file
raf.writeUTF("Hello, this is a RandomAccessFile demo!");
raf.writeInt(100);
raf.writeDouble(99.99);
System.out.println("Data written to the file successfully.");
// Move the file pointer to the beginning for reading
raf.seek(0);
// Reading data from the file
System.out.println("Reading Data:");
System.out.println("String: " + raf.readUTF());
System.out.println("Integer: " + raf.readInt());
System.out.println("Double: " + raf.readDouble());
// Modifying a specific position (Overwriting integer value)
raf.seek(raf.length() - 12); // Moving pointer to the integer position
raf.writeInt(200); // Overwriting the integer 100 with 200
System.out.println("Integer value modified successfully.");
// Appending data at the end of the file
raf.seek(raf.length());
raf.writeUTF(" Additional data appended.");
System.out.println("Data appended successfully.");
// Close the file
raf.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
// Reading the modified file content
readFile(fileName);
}
// Method to read the file and display content after modifications
public static void readFile(String fileName) {
try {
RandomAccessFile raf = new RandomAccessFile(fileName, "r");
// Reading updated content
System.out.println("\nUpdated File Content:");
System.out.println("String: " + raf.readUTF());
System.out.println("Modified Integer: " + raf.readInt());
System.out.println("Double: " + raf.readDouble());
System.out.println("Appended String: " + raf.readUTF());
raf.close();
} catch (IOException e) {
System.out.println("Error while reading file: " + e.getMessage());
}
}
}
OUTPUT:
Data written to the file successfully.
Reading Data: String:
Hello, this is a RandomAccessFile demo!
Integer: 100
Double: 99.99
Integer value modified successfully.
Data appended successfully.
Updated File Content:
String: Hello, this is a RandomAccessFile demo! Modified Integer: 200 Double: 99.99
Appended String: Additional data appended.
5. Write a Java program to demonstrate the working of different collection classes. [Use package structure to store multiple classes].
CollectionDemo/
│── src/
│ ├── mycollections/
│ │ ├── ListExample.java
│ │ ├── SetExample.java
│ │ ├── MapExample.java
│ │ ├── MainDemo.java
Step 1: Create the Package Structure
Inside your src folder, create a package named mycollections.
Each class inside this package will demonstrate a different collection class.
1️⃣List Example (ArrayList)
package mycollections;
import java.util.ArrayList;
public class ListExample {
public void demonstrateList() {
ArrayList<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice"); // Duplicates allowed
// Iterating
System.out.println("ArrayList Elements:");
for (String name : names) {
System.out.println(name);
}
// Removing an element
names.remove("Bob");
System.out.println("After Removing 'Bob': " + names);
}
}
2️⃣Set Example (HashSet)
package mycollections;
import java.util.HashSet;
public class SetExample {
public void demonstrateSet() {
HashSet<Integer> numbers = new HashSet<>();
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(10); // Duplicate ignored
// Iterating
System.out.println("HashSet Elements:");
for (int num : numbers) {
System.out.println(num);
}
// Checking if an element exists
System.out.println("Contains 20? " + numbers.contains(20));
}
}
3️⃣Map Example (HashMap)
package mycollections;
import java.util.HashMap;
public class MapExample {
public void demonstrateMap() {
HashMap<Integer, String> students = new HashMap<>();
// Adding key-value pairs
students.put(101, "Alice");
students.put(102, "Bob");
students.put(103, "Charlie");
// Iterating through the map
System.out.println("HashMap Elements:");
for (Integer key : students.keySet()) {
System.out.println("ID: " + key + ", Name: " + students.get(key));
}
// Removing an entry
students.remove(102);
System.out.println("After Removing ID 102: " + students);
}
}
Step 3: Main Class to Run All Examples
package mycollections;
public class MainDemo {
public static void main(String[] args) {
ListExample listDemo = new ListExample();
SetExample setDemo = new SetExample();
MapExample mapDemo = new MapExample();
listDemo.demonstrateList();
System.out.println();
setDemo.demonstrateSet();
System.out.println();
mapDemo.demonstrateMap();
}
}
OUTPUT:
ArrayList Elements:
Alice
Bob
Charlie
Alice
After Removing 'Bob':
[Alice, Charlie, Alice]
HashSet Elements:
10
20
30
Contains 20? true
HashMap Elements:
ID: 101,
Name: Alice
ID: 102,
Name: Bob
ID: 103,
Name: Charlie
After Removing ID 102: {101=Alice, 103=Charlie}
6. 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.]
Synchronization: Ensures only one thread can book a ticket at a time.
Multiple Threads: Simulates multiple users trying to book tickets.
Shared Resource: A single TicketBooking object representing a ticket counte
// TicketBooking.java (Shared Resource)
class TicketBooking {
private int availableSeats = 5; // Total available seats
// Synchronized method to book a ticket
public synchronized void bookTicket(String passenger, int requestedSeats) {
System.out.println(passenger + " is trying to book " + requestedSeats + "
seat(s).");
if (requestedSeats <= availableSeats) {
System.out.println("Booking successful for " + passenger + "! Seats booked:
" + requestedSeats);
availableSeats -= requestedSeats;
} else {
System.out.println("Booking failed for " + passenger + "! Not enough seats
available.");
}
System.out.println("Seats left: " + availableSeats);
}
}
// Passenger Thread (Each user trying to book a ticket)
class Passenger extends Thread {
private TicketBooking ticketCounter;
private String passengerName;
private int seatsNeeded;
public Passenger(TicketBooking ticketCounter, String passengerName, int
seatsNeeded) {
this.ticketCounter = ticketCounter;
this.passengerName = passengerName;
this.seatsNeeded = seatsNeeded;
}
@Override
public void run() {
ticketCounter.bookTicket(passengerName, seatsNeeded);
}
}
// Main Class
public class RailwayReservation {
public static void main(String[] args) {
TicketBooking ticketCounter = new TicketBooking(); // Shared resource
// Creating multiple passenger threads
Passenger p1 = new Passenger(ticketCounter, "Alice", 2);
Passenger p2 = new Passenger(ticketCounter, "Bob", 1);
Passenger p3 = new Passenger(ticketCounter, "Charlie", 3);
Passenger p4 = new Passenger(ticketCounter, "David", 2);
// Start threads
p1.start();
p2.start();
p3.start();
p4.start();
}
}
OUTPUT
Alice is trying to book 2 seat(s).
Booking successful for Alice! Seats booked: 2
Seats left: 3
Bob is trying to book 1 seat(s).
Booking successful for Bob! Seats booked: 1
Seats left: 2
Charlie is trying to book 3 seat(s).
Booking failed for Charlie! Not enough seats available.
Seats left: 2
David is trying to book 2 seat(s).
Booking successful for David! Seats booked: 2
Seats left: 0
7. Write a program to perform CRUD operations on the student table in a database using JDBC.
JDBC connection to a MySQL database
Perform Create, Read, Update, Delete operations
CREATE DATABASE CollegeDB;
USE CollegeDB;
CREATE TABLE student (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
course VARCHAR(50)
);
Java Program for CRUD Operations
import java.sql.*;
import java.util.Scanner;
public class StudentCRUD {
// Database connection details
private static final String URL = "jdbc:mysql://localhost:3306/CollegeDB";
private static final String USER = "root"; // Change if necessary
private static final String PASSWORD = ""; // Change if necessary
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.println("\n1. Insert Student\n2. View Students\n3. Update
Student\n4. Delete Student\n5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
switch (choice) {
case 1 -> insertStudent(conn, scanner);
case 2 -> viewStudents(conn);
case 3 -> updateStudent(conn, scanner);
case 4 -> deleteStudent(conn, scanner);
case 5 -> System.exit(0);
default -> System.out.println("Invalid choice! Try again.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void insertStudent(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
System.out.print("Enter Course: ");
String course = scanner.next();
String sql = "INSERT INTO student (name, age, course) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, course);
pstmt.executeUpdate();
System.out.println("Student added successfully.");
}
}
private static void viewStudents(Connection conn) throws SQLException {
String sql = "SELECT * FROM student";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("\nID | Name | Age | Course");
while (rs.next()) {
System.out.printf("%d | %s | %d | %s\n", rs.getInt("id"), rs.getString("name"),
rs.getInt("age"), rs.getString("course"));
}
}
}
private static void updateStudent(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID to Update: ");
int id = scanner.nextInt();
System.out.print("Enter New Course: ");
String course = scanner.next();
String sql = "UPDATE student SET course = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, course);
pstmt.setInt(2, id);
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) System.out.println("Student updated successfully.");
else System.out.println("Student not found.");
}
}
private static void deleteStudent(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID to Delete: ");
int id = scanner.nextInt();
String sql = "DELETE FROM student WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
int rowsDeleted = pstmt.executeUpdate();
if (rowsDeleted > 0) System.out.println("Student deleted successfully.");
else System.out.println("Student not found.");
}
}
}
8. 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
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private double num1, num2, result;
private char operator;
public Calculator() {
setTitle("Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
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);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789".contains(command)) {
textField.setText(textField.getText() + command);
} else if ("+-*/".contains(command)) {
num1 = Double.parseDouble(textField.getText());
operator = command.charAt(0);
textField.setText("");
} else if (command.equals("=")) {
num2 = Double.parseDouble(textField.getText());
try {
switch (operator) {
case '+' -> result = num1 + num2;
case '-' -> result = num1 - num2;
case '*' -> result = num1 * num2;
case '/' -> {
if (num2 == 0) throw new ArithmeticException("Cannot divide by
zero");
result = num1 / num2;
}
}
textField.setText(String.valueOf(result));
} catch (ArithmeticException ex) {
textField.setText("Error");
}
} else if (command.equals("C")) {
textField.setText("");
}
}
public static void main(String[] args) {
new Calculator();
}
}
9. 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]
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseEventDemo extends JFrame {
private JLabel label;
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
label = new JLabel("Perform a Mouse Event", JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 16));
add(label, BorderLayout.CENTER);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}
});
setVisible(true);
}
public static void main(String[] args) {
new MouseEventDemo();
}
}