■ Java OOP
Practical Lab Notes
VSE-281-AID · Object Oriented Programming
Second Year AI & Data Science · 2024 Pattern · SPPU
Covers all 4 Parts · Part A · B · C · D
With complete Java code for every assignment
Savitribai Phule Pune University
VSE-281-AID · OOP Practical Notes · Page 1
Table of Contents
# Topic Part
1 A1 — Calculator with error handling A
2 A2 — E-Commerce order processing A
3 A3 — Method overloading (power & abs) A
4 A4 — Library Management System A
5 A5 — Array operations A
6 A6 — Hotel Room Booking (2D arrays) A
7 B1 — Single Inheritance B
8 B2 — Interfaces & Polymorphism B
9 B3 — Abstract Classes B
10 B4 — ATM Machine (Exception Handling) B
11 B5 — Online Shopping (Exceptions) B
12 B6 — Stock Price Monitor (Threads) B
13 B7 — Chat System (Multithreading) B
14 C1 — Employee JDBC CRUD C
15 C2 — Student JDBC CRUD C
16 D — Banking System (Mini Project) D
VSE-281-AID · OOP Practical Notes · Page 2
Part A — Classes, Objects & Arrays
Part A — Assignment 1: Calculator with Dynamic Input & Error Handling
A console calculator that reads an expression, evaluates it, and handles division-by-zero and invalid input using
try-catch.
Java Code
import [Link];
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("=== Java Calculator ===");
boolean running = true;
while (running) {
try {
[Link]("Enter number1: ");
double a = [Link]([Link]().trim());
[Link]("Operator (+,-,*,/,%,exit): ");
String op = [Link]().trim();
if ([Link]("exit")) { running = false; break; }
[Link]("Enter number2: ");
double b = [Link]([Link]().trim());
double result = switch (op) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> {
if (b == 0) throw new ArithmeticException("Div by zero!");
yield a / b;
VSE-281-AID · OOP Practical Notes · Page 3
case "%" -> a % b;
default -> throw new IllegalArgumentException("Unknown op: " + op);
};
[Link]("Result: %.4f%n", result);
} catch (NumberFormatException e) {
[Link]("[Error] Invalid number: " + [Link]());
} catch (ArithmeticException | IllegalArgumentException e) {
[Link]("[Error] " + [Link]());
[Link]("Bye!");
■ Key concepts: switch expressions (Java 14+), NumberFormatException, ArithmeticException, while loop for continuous
input.
Part A — Assignment 2: E-Commerce Order Processing
Demonstrates multiple constructors, dynamic product input, total cost computation, discount policy, and invoice
printing.
Java Code
import [Link]; import [Link];
class Product {
String name; double price; int qty;
// Constructor 1 — default
Product() { this("Unknown", 0, 1); }
// Constructor 2 — name + price
Product(String name, double price) { this(name, price, 1); }
// Constructor 3 — all fields
Product(String name, double price, int qty) {
[Link]=name; [Link]=price; [Link]=qty;
VSE-281-AID · OOP Practical Notes · Page 4
}
double subtotal() { return price * qty; }
public String toString() {
return [Link]("%-20s Rs.%-8.2f x%d = Rs.%.2f",
name, price, qty, subtotal());
public class ECommerce {
static double applyDiscount(double total) {
if (total > 5000) return total * 0.90; // 10% off
if (total > 2000) return total * 0.95; // 5% off
return total;
public static void main(String[] args) {
ArrayList<Product> cart = new ArrayList<>();
// Pre-loaded products via constructors
[Link](new Product("Laptop Bag", 799, 1));
[Link](new Product("USB Hub", 349));
// User input
Scanner sc = new Scanner([Link]);
[Link]("Add product (name price qty): ");
[Link](new Product([Link](), [Link](), [Link]()));
// Invoice
double gross = [Link]().mapToDouble(Product::subtotal).sum();
double net = applyDiscount(gross);
[Link]("\n====== INVOICE ======");
[Link]([Link]::println);
[Link]("Gross: Rs.%.2f%n", gross);
VSE-281-AID · OOP Practical Notes · Page 5
[Link]("Net : Rs.%.2f (%.0f%% discount)%n",
net, (1 - net/gross)*100);
■ Key concepts: constructor chaining with this(), ArrayList, streams, method references, printf formatting.
Part A — Assignment 3: Method Overloading — Power & Absolute Value
Overloads compute power and absolute value for int, long, float, and double. Also demonstrates Math class
static methods for comparison.
Java Code
public class MathOps {
// --- Overloaded power ---
static int power(int b, int e) { return (int)[Link](b, e); }
static long power(long b, int e) { return (long)[Link](b, e); }
static float power(float b, int e) { return (float)[Link](b, e); }
static double power(double b, int e) { return [Link](b, e); }
// --- Overloaded absolute ---
static int absolute(int x) { return x < 0 ? -x : x; }
static long absolute(long x) { return x < 0 ? -x : x; }
static float absolute(float x) { return x < 0 ? -x : x; }
static double absolute(double x) { return x < 0 ? -x : x; }
public static void main(String[] args) {
[Link]("power(2,10) = " + power(2, 10));
[Link]("power(2.5,3) = " + power(2.5, 3));
[Link]("[Link](2,10)= " + [Link](2, 10));
[Link]("absolute(-42) = " + absolute(-42));
[Link]("absolute(-3.7)= " + absolute(-3.7f));
[Link]("[Link](-42) = " + [Link](-42));
VSE-281-AID · OOP Practical Notes · Page 6
}
■ Method overloading is resolved at compile time (static polymorphism). The compiler picks the best-matching signature.
Part A — Assignment 4: Library Management System (static fields & methods)
Tracks books with a static counter. Supports add, issue, return, and view operations via a menu loop.
Java Code
import [Link]; import [Link];
class Book {
private static int totalBooks = 0;
private int id; private String title, author;
private boolean issued = false;
Book(String title, String author) {
[Link]=title; [Link]=author;
[Link] = ++totalBooks;
static int getTotalBooks() { return totalBooks; }
void issue() { issued = true; [Link](title + " issued."); }
void returnB(){ issued = false; [Link](title + " returned."); }
public String toString() {
return [Link]("[%d] %s by %s — %s",
id, title, author, issued ? "ISSUED" : "Available");
public class Library {
public static void main(String[] args) {
ArrayList<Book> shelf = new ArrayList<>();
Scanner sc = new Scanner([Link]);
VSE-281-AID · OOP Practical Notes · Page 7
[Link](new Book("Clean Code", "Robert Martin"));
[Link](new Book("Head First Java", "Kathy Sierra"));
int ch;
do {
[Link]("\[Link] [Link] [Link] [Link] [Link]");
ch = [Link]();
switch(ch) {
case 1 -> [Link]([Link]::println);
case 2 -> { [Link]("Book ID: ");
[Link]([Link]()-1).issue(); }
case 3 -> { [Link]("Book ID: ");
[Link]([Link]()-1).returnB(); }
case 4 -> [Link]("Total: " + [Link]());
} while(ch != 0);
■ static fields are shared across all objects. getTotalBooks() is a class-level method called on the class, not an instance.
Part A — Assignment 5: Array Operations
Performs display, max, min, sum, average, and linear search on a user-provided integer array.
Java Code
import [Link];
public class ArrayOps {
static void display(int[] a) {
[Link]("Array: ");
for(int x : a) [Link](x + " ");
[Link]();
VSE-281-AID · OOP Practical Notes · Page 8
static int max(int[] a) { int m=a[0]; for(int x:a) if(x>m) m=x; return m; }
static int min(int[] a) { int m=a[0]; for(int x:a) if(x<m) m=x; return m; }
static int sum(int[] a) { int s=0; for(int x:a) s+=x; return s; }
static double avg(int[] a){ return (double)sum(a)/[Link]; }
static int search(int[] a, int key) {
for(int i=0;i<[Link];i++) if(a[i]==key) return i;
return -1;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter size: "); int n = [Link]();
int[] arr = new int[n];
[Link]("Enter " + n + " elements:");
for(int i=0;i<n;i++) arr[i] = [Link]();
display(arr);
[Link]("Max: " + max(arr));
[Link]("Min: " + min(arr));
[Link]("Sum: " + sum(arr));
[Link] ("Avg: %.2f%n", avg(arr));
[Link]("Search key: "); int k = [Link]();
int idx = search(arr, k);
[Link](idx>=0 ? "Found at index "+idx : "Not found");
■ for-each loop is syntactic sugar — use it for read-only traversal. Use a regular for loop when you need the index.
VSE-281-AID · OOP Practical Notes · Page 9
Part A — Assignment 6: Hotel Room Booking — 2D Arrays
Models a hotel as a 2D boolean array [floors][rooms]. Shows available/booked status and lets a user book a
specific room.
Java Code
import [Link];
public class HotelBooking {
static final int FLOORS = 3, ROOMS = 4;
static boolean[][] hotel = new boolean[FLOORS][ROOMS]; // false=available
static void showRooms() {
[Link]("\nFloor | Room1 Room2 Room3 Room4");
[Link]("------|-------------------------------");
for(int f=0; f<FLOORS; f++) {
[Link](" %d |", f+1);
for(int r=0; r<ROOMS; r++)
[Link](" %-7s", hotel[f][r] ? "BOOKED" : "Free");
[Link]();
static void bookRoom(int floor, int room) {
if(hotel[floor][room]) {
[Link]("Room already booked!");
} else {
hotel[floor][room] = true;
[Link]("Room " + (room+1) + " on Floor " + (floor+1) + " booked!");
VSE-281-AID · OOP Practical Notes · Page 10
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int ch;
do {
[Link]("\[Link] Rooms [Link] Room [Link]");
ch = [Link]();
switch(ch) {
case 1 -> showRooms();
case 2 -> {
[Link]("Floor (1-3): "); int f = [Link]()-1;
[Link]("Room (1-4): "); int r = [Link]()-1;
if(f<0||f>=FLOORS||r<0||r>=ROOMS)
[Link]("Invalid selection!");
else bookRoom(f, r);
} while(ch != 0);
■ 2D array syntax: boolean[floors][rooms]. Access as hotel[floorIndex][roomIndex]. Both indices are 0-based.
VSE-281-AID · OOP Practical Notes · Page 11
Part B — Inheritance, Polymorphism & Threads
Part B — Assignment 1: Single Inheritance
A Vehicle superclass is extended by Car. The subclass calls the parent's display method using super and adds
its own attributes.
Java Code
class Vehicle {
String brand; int year;
Vehicle(String brand, int year) { [Link]=brand; [Link]=year; }
void display() {
[Link]("Brand: " + brand + ", Year: " + year);
class Car extends Vehicle {
int doors;
Car(String brand, int year, int doors) {
super(brand, year); // calls Vehicle constructor
[Link] = doors;
@Override
void display() {
[Link](); // calls parent method
[Link]("Doors: " + doors);
public class InheritanceDemo {
public static void main(String[] args) {
Car c = new Car("Toyota", 2023, 4);
VSE-281-AID · OOP Practical Notes · Page 12
[Link]();
[Link](c instanceof Vehicle); // true
■ Always call super() as the first statement in a subclass constructor to initialise the parent's fields.
Part B — Assignment 2: Interfaces & Polymorphism
A Shape interface with area() and perimeter() is implemented by Circle, Rectangle, and Triangle. Objects are
stored in a Shape array, showing runtime polymorphism.
Java Code
interface Shape {
double area();
double perimeter();
default void display() {
[Link]("Area=%.2f Perimeter=%.2f%n", area(), perimeter());
class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double area() { return [Link] * r * r; }
public double perimeter() { return 2 * [Link] * r; }
class Rectangle implements Shape {
double l, w;
Rectangle(double l, double w) { this.l=l; this.w=w; }
public double area() { return l * w; }
public double perimeter() { return 2*(l+w); }
VSE-281-AID · OOP Practical Notes · Page 13
class Triangle implements Shape {
double a, b, c;
Triangle(double a, double b, double c) { this.a=a; this.b=b; this.c=c; }
public double area() {
double s = (a+b+c)/2;
return [Link](s*(s-a)*(s-b)*(s-c)); // Heron's formula
public double perimeter() { return a + b + c; }
public class PolymorphismDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle(5), new Rectangle(4,6), new Triangle(3,4,5) };
for(Shape s : shapes) {
[Link]([Link]().getSimpleName() + " — ");
[Link]();
■ A class can implement multiple interfaces. default methods in interfaces (Java 8+) provide a fallback implementation.
Part B — Assignment 3: Abstract Classes
An abstract Animal class declares an abstract makeSound(). Dog and Cat extend it and provide concrete
implementations.
Java Code
abstract class Animal {
String name;
Animal(String name) { [Link] = name; }
abstract void makeSound(); // must be overridden
void sleep() { [Link](name + " is sleeping..."); }
VSE-281-AID · OOP Practical Notes · Page 14
}
class Dog extends Animal {
Dog(String name) { super(name); }
@Override
void makeSound() { [Link](name + " says: Woof!"); }
class Cat extends Animal {
Cat(String name) { super(name); }
@Override
void makeSound() { [Link](name + " says: Meow!"); }
public class AbstractDemo {
public static void main(String[] args) {
Animal[] animals = { new Dog("Bruno"), new Cat("Whiskers") };
for(Animal a : animals) {
[Link]();
[Link]();
// Animal a = new Animal("x"); // ERROR — cannot instantiate abstract class
■ Difference: abstract class can have state (fields) and non-abstract methods. Interface (pre-Java 8) can only have
constants and abstract methods.
VSE-281-AID · OOP Practical Notes · Page 15
Part B — Assignment 4: ATM Machine — Exception Handling
Simulates an ATM with balance check, deposit, and withdraw. Uses custom exceptions, try-catch-finally, and
loops for a persistent session.
Java Code
import [Link];
class InsufficientFundsException extends ArithmeticException {
InsufficientFundsException(double bal, double amt) {
super([Link]("Cannot withdraw Rs.%.2f. Balance: Rs.%.2f", amt, bal));
class ATM {
private double balance;
ATM(double bal) { [Link] = bal; }
void deposit(double amt) {
if(amt <= 0) throw new IllegalArgumentException("Amount must be > 0");
balance += amt;
[Link]("Deposited Rs.%.2f. New balance: Rs.%.2f%n", amt, balance);
void withdraw(double amt) {
if(amt <= 0) throw new IllegalArgumentException("Amount must be > 0");
if(amt > balance) throw new InsufficientFundsException(balance, amt);
balance -= amt;
[Link]("Withdrawn Rs.%.2f. Remaining: Rs.%.2f%n", amt, balance);
void checkBalance() { [Link]("Balance: Rs.%.2f%n", balance); }
VSE-281-AID · OOP Practical Notes · Page 16
}
public class ATMDemo {
public static void main(String[] args) {
ATM atm = new ATM(10000);
Scanner sc = new Scanner([Link]);
int ch;
do {
[Link]("\[Link] [Link] [Link] [Link]");
ch = [Link]();
try {
switch(ch) {
case 1 -> [Link]();
case 2 -> { [Link]("Amount: "); [Link]([Link]()); }
case 3 -> { [Link]("Amount: "); [Link]([Link]()); }
} catch(InsufficientFundsException e) {
[Link]("[Insufficient Funds] " + [Link]());
} catch(IllegalArgumentException e) {
[Link]("[Invalid Input] " + [Link]());
} finally {
[Link]("--- Transaction complete ---");
} while(ch != 0);
■ finally block ALWAYS executes — even if an exception is thrown or caught. Use it for cleanup (closing resources,
logging).
Part B — Assignment 5: Online Shopping System — Exception Handling
VSE-281-AID · OOP Practical Notes · Page 17
Cart management with add-item, total calculation, and payment processing. Handles NumberFormatException
and ArithmeticException.
Java Code
import [Link].*; import [Link];
public class OnlineShopping {
static Map<String,Double> cart = new LinkedHashMap<>();
static void addItem(String name, String priceStr) {
try {
double price = [Link](priceStr);
if(price <= 0) throw new ArithmeticException("Price must be positive");
[Link](name, price);
[Link](name + " added at Rs." + price);
} catch(NumberFormatException e) {
[Link]("[Error] Invalid price: " + priceStr);
} catch(ArithmeticException e) {
[Link]("[Error] " + [Link]());
static double total() {
return [Link]().stream().mapToDouble(Double::doubleValue).sum();
static void processPayment(String amtStr) {
try {
double paid = [Link](amtStr);
double bill = total();
if(bill == 0) throw new ArithmeticException("Cart is empty!");
VSE-281-AID · OOP Practical Notes · Page 18
double change = paid - bill;
if(change < 0) throw new ArithmeticException("Insufficient payment!");
[Link]("Paid: Rs.%.2f Bill: Rs.%.2f Change: Rs.%.2f%n",
paid, bill, change);
} catch(NumberFormatException e) {
[Link]("[Error] Invalid amount.");
} catch(ArithmeticException e) {
[Link]("[Error] " + [Link]());
} finally {
[Link]("Payment gateway closed.");
public static void main(String[] args) {
addItem("Phone", "15999");
addItem("Cover", "abc"); // triggers NumberFormatException
addItem("Cable", "-50"); // triggers ArithmeticException
addItem("Cable", "299");
[Link]("Total: Rs." + total());
processPayment("20000");
■ LinkedHashMap preserves insertion order — good for cart display. Multiple catch blocks handle different exception
types separately.
VSE-281-AID · OOP Practical Notes · Page 19
Part B — Assignment 6: Stock Price Monitor — Two Threads
One thread fetches (simulates) stock prices; another displays them. Uses synchronized shared resource,
[Link](), and join().
Java Code
import [Link].*;
class StockData {
private double price = 100.0;
private boolean updated = false;
synchronized void setPrice(double p) {
price = p; updated = true;
[Link]("[Fetcher] Price set: Rs.%.2f%n", p);
notifyAll();
synchronized double getPrice() throws InterruptedException {
while(!updated) wait();
updated = false;
return price;
class Fetcher extends Thread {
StockData data; Random rnd = new Random();
Fetcher(StockData d) { data=d; setName("Fetcher"); }
public void run() {
for(int i=0; i<5; i++) {
try {
[Link](1000); // simulate API delay
[Link](100 + [Link]()*50);
VSE-281-AID · OOP Practical Notes · Page 20
} catch(InterruptedException e) { [Link]().interrupt(); }
class Displayer extends Thread {
StockData data;
Displayer(StockData d) { data=d; setName("Displayer"); }
public void run() {
for(int i=0; i<5; i++) {
try {
double p = [Link]();
[Link]("[Display] Current Price: Rs.%.2f%n", p);
} catch(InterruptedException e) { [Link]().interrupt(); }
public class StockMonitor {
public static void main(String[] args) throws InterruptedException {
StockData sd = new StockData();
Thread f = new Fetcher(sd), d = new Displayer(sd);
[Link](); [Link]();
[Link](); [Link](); // wait for both threads
[Link]("Done.");
■ synchronized prevents race conditions. wait() releases the lock and blocks; notifyAll() wakes waiting threads. join()
makes main wait until a thread finishes.
VSE-281-AID · OOP Practical Notes · Page 21
Part B — Assignment 7: Multi-threaded Chat System
Each user is a thread. Demonstrates isAlive(), join(), thread priorities, and simulated suspend/resume/stop.
Java Code
import [Link].*;
class ChatUser extends Thread {
private String[] messages;
private volatile boolean suspended = false, stopped = false;
ChatUser(String name, String[] msgs, int priority) {
super(name);
[Link] = msgs;
setPriority(priority);
public void run() {
for(String msg : messages) {
if(stopped) break;
synchronized(this) {
while(suspended) {
try { wait(); } catch(InterruptedException e) { return; }
[Link]("[" + getName() + "]: " + msg);
try { [Link](500); } catch(InterruptedException e) { return; }
synchronized void suspendUser() { suspended = true; }
synchronized void resumeUser() { suspended = false; notifyAll(); }
void stopUser() { stopped = true; interrupt(); }
VSE-281-AID · OOP Practical Notes · Page 22
}
public class ChatDemo {
public static void main(String[] args) throws InterruptedException {
ChatUser alice = new ChatUser("Alice",
new String[]{"Hello!","How are you?","Bye!"}, Thread.MAX_PRIORITY);
ChatUser bob = new ChatUser("Bob",
new String[]{"Hi Alice","I'm good!","See ya!"}, Thread.NORM_PRIORITY);
[Link](); [Link]();
[Link]("Alice alive? " + [Link]());
[Link](600);
[Link]();
[Link]("[System] Bob suspended");
[Link](1000);
[Link]();
[Link]("[System] Bob resumed");
[Link](); [Link]();
[Link]("Chat ended.");
■ volatile ensures visibility of stopped/suspended flags across threads. Thread.MAX_PRIORITY=10, MIN=1, NORM=5.
Higher priority threads get more CPU time but it's not guaranteed.
VSE-281-AID · OOP Practical Notes · Page 23
Part C — JDBC Database Connectivity
JDBC Setup Checklist
1. Install MySQL: sudo apt install mysql-server (or use XAMPP)
2. Download MySQL JDBC driver ([Link])
3. Add to classpath: javac -cp .:[Link] *.java
4. Run: java -cp .:[Link] ClassName
5. Connection URL: jdbc:mysql://localhost:3306/dbname
Part C — Assignment 1: Employee Management — JDBC CRUD
Connects to MySQL, creates an employees table, and performs Create, Read, Update, Delete using
PreparedStatement.
SQL — Run once to create database
CREATE DATABASE IF NOT EXISTS company;
USE company;
CREATE TABLE IF NOT EXISTS employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
dept VARCHAR(50),
salary DOUBLE
);
Java Code — Employee CRUD
import [Link].*;
public class EmployeeCRUD {
static final String URL = "jdbc:mysql://localhost:3306/company";
static final String USER = "root";
static final String PASS = "your_password";
static Connection connect() throws SQLException {
return [Link](URL, USER, PASS);
VSE-281-AID · OOP Practical Notes · Page 24
}
// CREATE
static void addEmployee(String name, String dept, double sal) {
String sql = "INSERT INTO employees(name,dept,salary) VALUES(?,?,?)";
try(Connection c=connect(); PreparedStatement ps=[Link](sql)) {
[Link](1, name); [Link](2, dept); [Link](3, sal);
[Link]();
[Link]("Added: " + name);
} catch(SQLException e) { [Link](); }
// READ
static void viewAll() {
try(Connection c=connect(); Statement st=[Link]()) {
ResultSet rs = [Link]("SELECT * FROM employees");
[Link]("ID | Name | Dept | Salary");
[Link]("---|-----------------|------------|--------");
while([Link]())
[Link]("%-3d| %-16s| %-11s| %.2f%n",
[Link]("id"), [Link]("name"),
[Link]("dept"), [Link]("salary"));
} catch(SQLException e) { [Link](); }
// UPDATE
static void updateSalary(int id, double newSal) {
String sql = "UPDATE employees SET salary=? WHERE id=?";
try(Connection c=connect(); PreparedStatement ps=[Link](sql)) {
VSE-281-AID · OOP Practical Notes · Page 25
[Link](1, newSal); [Link](2, id);
int rows = [Link]();
[Link](rows + " row(s) updated.");
} catch(SQLException e) { [Link](); }
// DELETE
static void deleteEmployee(int id) {
String sql = "DELETE FROM employees WHERE id=?";
try(Connection c=connect(); PreparedStatement ps=[Link](sql)) {
[Link](1, id);
int rows = [Link]();
[Link](rows + " row(s) deleted.");
} catch(SQLException e) { [Link](); }
public static void main(String[] args) {
addEmployee("Samee Khan", "AI Dept", 75000);
addEmployee("Rahul Mehta", "Data Eng", 68000);
viewAll();
updateSalary(1, 80000);
deleteEmployee(2);
viewAll();
■ Always use PreparedStatement over Statement — it prevents SQL injection and improves performance.
try-with-resources auto-closes Connection/Statement.
VSE-281-AID · OOP Practical Notes · Page 26
Part C — Assignment 2: Student Management — JDBC CRUD with Transactions
Full CRUD for student records. Adds transaction management (commit/rollback) to ensure data integrity.
SQL
CREATE DATABASE IF NOT EXISTS university;
USE university;
CREATE TABLE IF NOT EXISTS students (
roll_no INT PRIMARY KEY,
name VARCHAR(100),
branch VARCHAR(50),
cgpa DOUBLE
);
Java Code — Student CRUD with Transaction
import [Link].*;
public class StudentCRUD {
static final String URL = "jdbc:mysql://localhost:3306/university";
static final String USER = "root", PASS = "your_password";
static void addStudentWithTransaction(int roll, String name,
String branch, double cgpa) {
String sql = "INSERT INTO students VALUES(?,?,?,?)";
Connection c = null;
try {
c = [Link](URL, USER, PASS);
[Link](false); // begin transaction
PreparedStatement ps = [Link](sql);
[Link](1, roll); [Link](2, name);
[Link](3, branch); [Link](4, cgpa);
[Link]();
[Link](); // commit
VSE-281-AID · OOP Practical Notes · Page 27
[Link]("Student added: " + name);
} catch(SQLException e) {
[Link]("Error! Rolling back...");
try { if(c!=null) [Link](); } catch(SQLException ex) {}
} finally {
try { if(c!=null) [Link](); } catch(SQLException e) {}
static void viewAll() {
try(Connection c=[Link](URL,USER,PASS);
Statement st=[Link]()) {
ResultSet rs = [Link]("SELECT * FROM students ORDER BY roll_no");
[Link]("Roll | Name | Branch | CGPA");
while([Link]())
[Link]("%-5d| %-17s| %-7s| %.2f%n",
[Link](1), [Link](2),
[Link](3), [Link](4));
} catch(SQLException e) { [Link](); }
public static void main(String[] args) {
addStudentWithTransaction(101, "Samee Khan", "AIDS", 9.1);
addStudentWithTransaction(102, "Priya Sharma","CE", 8.7);
viewAll();
■ setAutoCommit(false) starts a manual transaction. Use commit() on success and rollback() on failure to maintain ACID
properties.
VSE-281-AID · OOP Practical Notes · Page 28
Part D — Mini Project: Banking System
A complete banking application demonstrating OOP principles: encapsulation, inheritance (SavingsAccount
extends BankAccount), exception handling, and a menu-driven interface.
[Link] — Base class
public class BankAccount {
private String accNo, holderName;
private double balance;
private static int counter = 1000;
BankAccount(String name, double initial) {
[Link] = name;
[Link] = initial;
[Link] = "ACC" + (++counter);
void deposit(double amt) {
if(amt <= 0) throw new IllegalArgumentException("Deposit must be > 0");
balance += amt;
[Link]("Deposited Rs.%.2f. Balance: Rs.%.2f%n", amt, balance);
void withdraw(double amt) {
if(amt <= 0) throw new IllegalArgumentException("Withdrawal must be > 0");
if(amt > balance) throw new ArithmeticException("Insufficient balance!");
balance -= amt;
[Link]("Withdrawn Rs.%.2f. Balance: Rs.%.2f%n", amt, balance);
double getBalance() { return balance; }
VSE-281-AID · OOP Practical Notes · Page 29
String getAccNo() { return accNo; }
String getHolderName() { return holderName; }
void displayInfo() {
[Link]("Account No : " + accNo);
[Link]("Holder : " + holderName);
[Link] ("Balance : Rs.%.2f%n", balance);
[Link] — Inherits BankAccount
public class SavingsAccount extends BankAccount {
private double dailyWithdrawLimit;
private double withdrawnToday = 0;
SavingsAccount(String name, double initial, double limit) {
super(name, initial);
[Link] = limit;
@Override
void withdraw(double amt) {
if(withdrawnToday + amt > dailyWithdrawLimit)
throw new ArithmeticException(
[Link]("Daily limit exceeded! Limit: Rs.%.2f, Used: Rs.%.2f",
dailyWithdrawLimit, withdrawnToday));
[Link](amt);
withdrawnToday += amt;
void resetDailyLimit() {
VSE-281-AID · OOP Practical Notes · Page 30
withdrawnToday = 0;
[Link]("Daily limit reset.");
@Override
void displayInfo() {
[Link]();
[Link]("Daily Limit: Rs.%.2f (Used: Rs.%.2f)%n",
dailyWithdrawLimit, withdrawnToday);
[Link] — Main menu driver
import [Link].*;
public class BankingSystem {
public static void main(String[] args) {
Map<String, SavingsAccount> bank = new HashMap<>();
Scanner sc = new Scanner([Link]);
int ch;
do {
[Link]("\n====== BANKING SYSTEM ======");
[Link]("1. Create Account");
[Link]("2. Deposit");
[Link]("3. Withdraw");
[Link]("4. Check Balance");
[Link]("5. Account Info");
[Link]("6. Reset Daily Limit");
[Link]("0. Exit");
[Link]("Choice: "); ch = [Link]();
try {
VSE-281-AID · OOP Practical Notes · Page 31
switch(ch) {
case 1 -> {
[Link]();
[Link]("Name: "); String nm = [Link]();
[Link]("Initial: "); double ini = [Link]();
[Link]("Daily limit: "); double lim = [Link]();
SavingsAccount sa = new SavingsAccount(nm, ini, lim);
[Link]([Link](), sa);
[Link]("Created! Account No: " + [Link]());
case 2,3,4,5,6 -> {
[Link]("Account No: "); String acc = [Link]();
SavingsAccount sa = [Link](acc);
if(sa == null) { [Link]("Account not found!"); break; }
switch(ch) {
case 2 -> { [Link]("Amount: "); [Link]([Link]()); }
case 3 -> { [Link]("Amount: "); [Link]([Link]()); }
case 4 -> [Link]("Balance: Rs.%.2f%n", [Link]());
case 5 -> [Link]();
case 6 -> [Link]();
} catch(ArithmeticException | IllegalArgumentException e) {
[Link]("[Error] " + [Link]());
} while(ch != 0);
[Link]("Thank you for banking with us!");
VSE-281-AID · OOP Practical Notes · Page 32
}
■ This project combines: encapsulation (private fields), inheritance (SavingsAccount extends BankAccount), method
overriding (@Override), exception handling, HashMap for multi-account support, and Scanner for interactive I/O.
VSE-281-AID · OOP Practical Notes · Page 33
Quick Reference Cheat Sheet
Concept Syntax / Key Point
Inheritance class Child extends Parent { }
Interface interface I { } | class C implements I { }
Abstract class abstract class A { abstract void m(); }
Method overloading Same name, different parameters (compile-time)
Method overriding @Override in subclass (runtime polymorphism)
super keyword super() — parent constructor | [Link]()
static field/method Shared across all instances; call via ClassName.x
this keyword Refers to current object; this() chains constructors
try-catch-finally finally always runs; use for cleanup
Custom exception class MyEx extends RuntimeException { }
Thread creation extends Thread or implements Runnable
Synchronization synchronized method/block — one thread at a time
JDBC steps Load driver → getConnection → prepareStatement → execute
PreparedStatement [Link](index, value); prevents SQL injection
2D array int[][] a = new int[rows][cols]; access a[r][c]
for-each for(Type x : array) — read-only iteration
ArrayList ArrayList<T> list = new ArrayList<>();
Lambda (streams) [Link]().filter(x->x>5).forEach([Link]::println)
VSE-281-AID · OOP Practical Notes · Page 34