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);
[Link] = 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) {
[Link](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) {
[Link] = radius;
}
public double calculateArea() {
return [Link] * radius * radius;
}
}
public class OOPDemo {
public static void main(String[] args) {
// Encapsulation
BankAccount account = new BankAccount();
[Link](1000);
[Link](200);
[Link]("Account Balance: " + [Link]());
// Inheritance
SavingsAccount savingsAccount = new SavingsAccount(5000, 0.05);
[Link]();
[Link]("Savings Account Balance: " + [Link]());
CheckingAccount checkingAccount = new CheckingAccount();
[Link](2000);
[Link](300);
[Link]("Checking Account Balance: " + [Link]());
// Polymorphism
Shape shape = new Circle(5.0);
[Link]("Area of the Circle: " + [Link]());
// 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 {
[Link](1500); // This will throw InsufficientBalanceException
} catch (InsufficientBalanceException e) {
[Link]("Error: " + [Link]());
}
try {
[Link](-500); // This will throw InvalidInputException
} catch (InvalidInputException e) {
[Link]("Error: " + [Link]());
}
// Real-time scenario: Handling exceptions when processing user data
try {
processUserData("John", -25);
} catch (InvalidInputException e) {
[Link]("Error: " + [Link]());
}
}
// Real-time scenario: Method that processes user data
public static void processUserData(String name, int age) {
if (name == null || [Link]() == 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
[Link]("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 [Link];
import [Link];
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// Create a RandomAccessFile for read and write operations
RandomAccessFile file = new RandomAccessFile("[Link]", "rw");
// Write data to the file
[Link]("Hello, World!");
[Link](42);
[Link](3.14159);
// Set the file pointer to the beginning of the file
[Link](0);
// Read and display the data
String str = [Link]();
int num = [Link]();
double pi = [Link]();
[Link]("String: " + str);
[Link]("Int: " + num);
[Link]("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 ([Link]() >= position + 1) {
[Link](position);
boolean bool = [Link]();
[Link]("Boolean: " + bool);
} else {
[Link]("Not enough data to read the boolean.");
}
// Close the file
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
OUTPUT:
5. Write a Java program to demonstrate the working of different collection classes. [Use package
structure to store multiple classes].
PROGRAM:
import [Link];
import [Link];
import [Link];
public class CollectionDemo {
public static void main(String[] args) {
// Demonstrating ArrayList
ArrayList<String> arrayList = new ArrayList<String>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("ArrayList Elements: " + arrayList);
// Demonstrating HashMap
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
[Link](1, "One");
[Link](2, "Two");
[Link](3, "Three");
[Link]("HashMap Elements: " + hashMap);
// Demonstrating HashSet
HashSet<String> hashSet = new HashSet<String>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("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 [Link];
class TicketBooking {
private int availableSeats;
private final ReentrantLock lock;
public TicketBooking(int totalSeats) {
availableSeats = totalSeats;
lock = new ReentrantLock();
}
public void bookTicket(int numSeats) {
[Link]();
try {
if (numSeats <= availableSeats) {
[Link]([Link]().getName() + " booked " + numSeats + "
seat(s).");
availableSeats -= numSeats;
} else {
[Link]([Link]().getName() + " couldn't book " + numSeats + "
seat(s). Insufficient seats.");
}
} finally {
[Link]();
}
}
}
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() {
[Link](3);
}
}, "Customer 1");
Thread customer2 = new Thread(new Runnable() {
public void run() {
[Link](4);
}
}, "Customer 2");
Thread customer3 = new Thread(new Runnable() {
public void run() {
[Link](2);
}
}, "Customer 3");
[Link]();
[Link]();
[Link]();
}
}
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 [Link].*;
import [Link].*;
import [Link];
import [Link];
public class SimpleCalculator {
public static void main(String[] args) {
[Link](new Runnable() {
public void run() {
JFrame frame = new CalculatorFrame();
[Link](JFrame.EXIT_ON_CLOSE);
[Link](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();
[Link]([Link]);
[Link](false);
add(display, [Link]);
JPanel buttonPanel = new JPanel(new GridLayout(5, 4));
add(buttonPanel, [Link]);
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
[Link](button);
[Link](new ButtonListener());
}
num1 = 0;
operator = "";
isNewInput = true;
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = [Link]();
if (isNewInput) {
[Link]("");
isNewInput = false;
}
if ([Link]("[0-9]")) {
[Link]([Link]() + input);
} else if ([Link]("C")) {
num1 = 0;
operator = "";
[Link]("");
} else if ([Link]("[/+\\-*]")) {
num1 = [Link]([Link]());
operator = input;
isNewInput = true;
} else if ([Link]("=")) {
try {
double num2 = [Link]([Link]());
double result = calculate(num1, num2, operator);
[Link]([Link](result));
isNewInput = true;
} catch (NumberFormatException e) {
[Link]("Error");
} catch (ArithmeticException e) {
[Link]("Divide by zero");
}
}
}
private double calculate(double num1, double num2, String operator) {
if ([Link]("+")) {
return num1 + num2;
} else if ([Link]("-")) {
return num1 - num2;
} else if ([Link]("*")) {
return num1 * num2;
} else if ([Link]("/")) {
if (num2 == 0) {
throw new ArithmeticException("Divide by zero");
}
return num1 / num2;
} else {
return num2;
}
}
}
}
OUTPUT: