Java Lab manual(CSIT&AIML)
Java Lab manual(CSIT&AIML)
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.
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.
TestClass.java file:
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);
}
}
}
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.
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;
// Using Encapsulation
System.out.println("Current Speed: " + myCar.getSpeed());
myCar.setSpeed(60);
System.out.println("Updated Speed: " + myCar.getSpeed());
· Inheritance:
Car extends Vehicle, inheriting the brand attribute and displayBrand() method.
· Polymorphism:
· 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.*;
4. Write a Java program on Random Access File class to perform different read and write operations.
import java.io.*;
try {
// Create a RandomAccessFile in "rw" mode (read-write)
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
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.
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
package mycollections;
import java.util.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);
}
}
// 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);
}
package mycollections;
import java.util.HashMap;
// Removing an entry
students.remove(102);
System.out.println("After Removing ID 102: " + students);
}
}
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).");
@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;
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
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();
}
}
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)) {
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 Calculator() {
setTitle("Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
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("");
}
}
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());
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked");
}
setVisible(true);
}