DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
Java programming
LAB MANUAL
Regulation : R22/JNTUH
Academic Year : 2023-2024
II B. TECH I SEMESTER
2. Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance,
Polymorphism and Abstraction]
// Encapsulation: Using private fields and public methods to access them
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
// Inheritance: Creating a subclass that inherits from a superclass
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(double initialBalance, double interestRate) {
deposit(initialBalance);
this.interestRate = interestRate;
}
public void applyInterest() {
double interest = getBalance() * interestRate;
deposit(interest);
}
}
// Polymorphism: Demonstrating polymorphism through method overriding
class CheckingAccount extends BankAccount {
public void withdraw(double amount) {
if (amount > 0) {
super.withdraw(amount); // Call the superclass method
}
}
}
// Abstraction: Creating an abstract class with an abstract method
abstract class Shape {
public abstract double calculateArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class OOPDemo {
public static void main(String[] args) {
// Encapsulation
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(200);
System.out.println("Account Balance: " + account.getBalance());
// Inheritance
SavingsAccount savingsAccount = new SavingsAccount(5000, 0.05);
savingsAccount.applyInterest();
System.out.println("Savings Account Balance: " + savingsAccount.getBalance());
CheckingAccount checkingAccount = new CheckingAccount();
checkingAccount.deposit(2000);
checkingAccount.withdraw(300);
System.out.println("Checking Account Balance: " + checkingAccount.getBalance());
// Polymorphism
Shape shape = new Circle(5.0);
System.out.println("Area of the Circle: " + shape.calculateArea());
// Abstraction
// Shape shape = new Shape(); // Error: Cannot instantiate an abstract class
}
}
OUTPUT:
3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the usage
of custom exceptions in real time scenario.
PROGRAM:
// Custom Checked Exception
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Custom Unchecked Exception
class InvalidInputException extends RuntimeException {
public InvalidInputException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
// Handle Checked Exception
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
}
balance -= amount;
}
// Handle Unchecked Exception
public void deposit(double amount) {
if (amount <= 0) {
throw new InvalidInputException("Invalid input: Amount must be greater than zero");
}
balance += amount;
}
public double getBalance() {
return balance;
}
}
public class ExceptionHandlingDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
try {
account.withdraw(1500); // This will throw InsufficientBalanceException
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
try {
account.deposit(-500); // This will throw InvalidInputException
} catch (InvalidInputException e) {
System.out.println("Error: " + e.getMessage());
}
// Real-time scenario: Handling exceptions when processing user data
try {
processUserData("John", -25);
} catch (InvalidInputException e) {
System.out.println("Error: " + e.getMessage());
}
}
// Real-time scenario: Method that processes user data
public static void processUserData(String name, int age) {
if (name == null || name.length() == 0) {
throw new InvalidInputException("Invalid name: Name cannot be empty");
}
if (age < 0) {
throw new InvalidInputException("Invalid age: Age cannot be negative");
}
// Process user data here
System.out.println("User Data Processed: Name - " + name + ", Age - " + age);
}
}
OUTPUT:
4. Write a Java program on Random Access File class to perform different read and write operations.
PROGRAM:
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// Create a RandomAccessFile for read and write operations
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
// Write data to the file
file.writeUTF("Hello, World!");
file.writeInt(42);
file.writeDouble(3.14159);
// Set the file pointer to the beginning of the file
file.seek(0);
// Read and display the data
String str = file.readUTF();
int num = file.readInt();
double pi = file.readDouble();
System.out.println("String: " + str);
System.out.println("Int: " + num);
System.out.println("Double: " + pi);
// Set the file pointer to a specific position (in bytes)
long position = 12;
// Check if there are enough bytes available to read a boolean
if (file.length() >= position + 1) {
file.seek(position);
boolean bool = file.readBoolean();
System.out.println("Boolean: " + bool);
} else {
System.out.println("Not enough data to read the boolean.");
}
// Close the file
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:
5. Write a Java program to demonstrate the working of different collection classes. [Use package
structure to store multiple classes].
PROGRAM:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class CollectionDemo {
public static void main(String[] args) {
// Demonstrating ArrayList
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
System.out.println("ArrayList Elements: " + arrayList);
// Demonstrating HashMap
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("HashMap Elements: " + hashMap);
// Demonstrating HashSet
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("Red");
hashSet.add("Green");
hashSet.add("Blue");
System.out.println("HashSet Elements: " + hashSet);
}
}
OUTPUT:
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.]
PROGRAM:
import java.util.concurrent.locks.ReentrantLock;
class TicketBooking {
private int availableSeats;
private final ReentrantLock lock;
public TicketBooking(int totalSeats) {
availableSeats = totalSeats;
lock = new ReentrantLock();
}
public void bookTicket(int numSeats) {
lock.lock();
try {
if (numSeats <= availableSeats) {
System.out.println(Thread.currentThread().getName() + " booked " + numSeats + "
seat(s).");
availableSeats -= numSeats;
} else {
System.out.println(Thread.currentThread().getName() + " couldn't book " + numSeats + "
seat(s). Insufficient seats.");
}
} finally {
lock.unlock();
}
}
}
public class MovieTicketBooking {
public static void main(String[] args) {
final TicketBooking booking = new TicketBooking(10); // 10 available seats
Thread customer1 = new Thread(new Runnable() {
public void run() {
booking.bookTicket(3);
}
}, "Customer 1");
Thread customer2 = new Thread(new Runnable() {
public void run() {
booking.bookTicket(4);
}
}, "Customer 2");
Thread customer3 = new Thread(new Runnable() {
public void run() {
booking.bookTicket(2);
}
}, "Customer 3");
customer1.start();
customer2.start();
customer3.start();
}
}
OUTPUT:
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
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class CalculatorFrame extends JFrame {
private JTextField display;
private double num1;
private String operator;
private boolean isNewInput;
public CalculatorFrame() {
setTitle("Simple Calculator");
setLayout(new BorderLayout());
setSize(300, 400);
display = new JTextField();
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(5, 4));
add(buttonPanel, BorderLayout.CENTER);
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
buttonPanel.add(button);
button.addActionListener(new ButtonListener());
}
num1 = 0;
operator = "";
isNewInput = true;
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (isNewInput) {
display.setText("");
isNewInput = false;
}
if (input.matches("[0-9]")) {
display.setText(display.getText() + input);
} else if (input.equals("C")) {
num1 = 0;
operator = "";
display.setText("");
} else if (input.matches("[/+\\-*]")) {
num1 = Double.parseDouble(display.getText());
operator = input;
isNewInput = true;
} else if (input.equals("=")) {
try {
double num2 = Double.parseDouble(display.getText());
double result = calculate(num1, num2, operator);
display.setText(String.valueOf(result));
isNewInput = true;
} catch (NumberFormatException e) {
display.setText("Error");
} catch (ArithmeticException e) {
display.setText("Divide by zero");
}
}
}
private double calculate(double num1, double num2, String operator) {
if (operator.equals("+")) {
return num1 + num2;
} else if (operator.equals("-")) {
return num1 - num2;
} else if (operator.equals("*")) {
return num1 * num2;
} else if (operator.equals("/")) {
if (num2 == 0) {
throw new ArithmeticException("Divide by zero");
}
return num1 / num2;
} else {
return num2;
}
}
}
}
OUTPUT: