Added Java lab programs

This commit is contained in:
2025-12-17 16:36:20 +05:30
parent ac2904f5db
commit 2f4beade3b
46 changed files with 882 additions and 0 deletions
Binary file not shown.
+39
View File
@@ -0,0 +1,39 @@
import accounts.Account;
import java.util.Scanner;
import services.Interest;
public class BankDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Account Number: ");
int accNo = sc.nextInt();
sc.nextLine();
System.out.print("Enter Customer Name: ");
String name = sc.nextLine();
System.out.print("Enter Initial Balance: ");
double balance = sc.nextDouble();
Account acc = new Account(accNo, name, balance);
System.out.print("Enter amount to deposit: ");
double dep = sc.nextDouble();
acc.deposit(dep);
System.out.print("Enter amount to withdraw: ");
double wd = sc.nextDouble();
acc.withdraw(wd);
Interest interest = new Interest();
double updatedBalance = interest.applyInterest(acc.getBalance());
System.out.println("\n--- Account Details After Interest ---");
acc.displayAccountDetails();
System.out.println("Balance after interest: " + updatedBalance);
sc.close();
}
}
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
package accounts;
public class Account {
private int accountNumber;
private String customerName;
private double balance;
public Account(int accountNumber, String customerName, double balance) {
this.accountNumber = accountNumber;
this.customerName = customerName;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Amount deposited: " + amount);
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Amount withdrawn: " + amount);
} else {
System.out.println("Insufficient balance!");
}
}
public double getBalance() {
return balance;
}
public void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Customer Name: " + customerName);
System.out.println("Balance: " + balance);
}
}
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
package services;
public class Interest {
private static final double RATE = 0.05; // 5% interest
public double applyInterest(double balance) {
return balance + (balance * RATE);
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+67
View File
@@ -0,0 +1,67 @@
import java.util.Scanner;
// -------- User-defined exception: TooOlder --------
class TooOlder extends Exception {
public TooOlder(String message) {
super(message);
}
}
// -------- User-defined exception: TooYounger --------
class TooYounger extends Exception {
public TooYounger(String message) {
super(message);
}
}
// -------- Employee class --------
class Employee {
String name;
int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
// Method to validate age eligibility
void validateAge() throws TooOlder, TooYounger {
if (age > 45) {
throw new TooOlder("Candidate is too old for recruitment");
} else if (age < 18) {
throw new TooYounger("Candidate is too young for recruitment");
} else {
System.out.println("Eligible");
System.out.println("Candidate Name: " + name);
}
}
}
// -------- Main class --------
public class EmployeeRecruitment {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Candidate Name: ");
String name = sc.nextLine();
System.out.print("Enter Candidate Age: ");
int age = sc.nextInt();
Employee emp = new Employee(name, age);
try {
emp.validateAge();
} catch (TooOlder e) {
System.out.println("Exception: " + e.getMessage());
} catch (TooYounger e) {
System.out.println("Exception: " + e.getMessage());
}
sc.close();
}
}
BIN
View File
Binary file not shown.
Binary file not shown.
+134
View File
@@ -0,0 +1,134 @@
import java.util.Scanner;
// ---------- SUPER CLASS ----------
class Car {
int speed;
double regularPrice;
String color;
Car(int speed, double regularPrice, String color) {
this.speed = speed;
this.regularPrice = regularPrice;
this.color = color;
}
double getSalePrice() {
return regularPrice;
}
}
// ---------- SUB CLASS : TRUCK ----------
class Truck extends Car {
int weight;
Truck(int speed, double regularPrice, String color, int weight) {
super(speed, regularPrice, color);
this.weight = weight;
}
double getSalePrice() {
if (weight > 2000) return regularPrice * 0.90;
// 10% discount
else return regularPrice * 0.80; // 20% discount
}
}
// ---------- SUB CLASS : FORD ----------
class Ford extends Car {
int year;
int manufacturerDiscount;
Ford(
int speed,
double regularPrice,
String color,
int year,
int manufacturerDiscount
) {
super(speed, regularPrice, color);
this.year = year;
this.manufacturerDiscount = manufacturerDiscount;
}
double getSalePrice() {
return super.getSalePrice() - manufacturerDiscount;
}
}
// ---------- SUB CLASS : SEDAN ----------
class Sedan extends Car {
int length;
Sedan(int speed, double regularPrice, String color, int length) {
super(speed, regularPrice, color);
this.length = length;
}
double getSalePrice() {
if (length > 20) return regularPrice * 0.95;
// 5% discount
else return regularPrice * 0.90; // 10% discount
}
}
// ---------- MAIN CLASS ----------
public class MyOwnAutoShop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ---- Sedan Object ----
System.out.println("Enter Sedan details:");
System.out.print("Speed: ");
int sSpeed = sc.nextInt();
System.out.print("Regular Price: ");
double sPrice = sc.nextDouble();
sc.nextLine();
System.out.print("Color: ");
String sColor = sc.nextLine();
System.out.print("Length: ");
int sLength = sc.nextInt();
Sedan sedan = new Sedan(sSpeed, sPrice, sColor, sLength);
// ---- Ford Object ----
System.out.println("\nEnter Ford details:");
System.out.print("Speed: ");
int fSpeed = sc.nextInt();
System.out.print("Regular Price: ");
double fPrice = sc.nextDouble();
sc.nextLine();
System.out.print("Color: ");
String fColor = sc.nextLine();
System.out.print("Year: ");
int fYear = sc.nextInt();
System.out.print("Manufacturer Discount: ");
int fDiscount = sc.nextInt();
Ford ford = new Ford(fSpeed, fPrice, fColor, fYear, fDiscount);
// ---- Car Object ----
System.out.println("\nEnter Car details:");
System.out.print("Speed: ");
int cSpeed = sc.nextInt();
System.out.print("Regular Price: ");
double cPrice = sc.nextDouble();
sc.nextLine();
System.out.print("Color: ");
String cColor = sc.nextLine();
Car car = new Car(cSpeed, cPrice, cColor);
// ---- Display Sale Prices ----
System.out.println("\n--- Sale Prices ---");
System.out.println("Sedan Sale Price: " + sedan.getSalePrice());
System.out.println("Ford Sale Price: " + ford.getSalePrice());
System.out.println("Car Sale Price: " + car.getSalePrice());
sc.close();
}
}
Binary file not shown.
Binary file not shown.
+94
View File
@@ -0,0 +1,94 @@
import java.util.Scanner;
// -------- BASE CLASS --------
class Payment {
double amount;
Payment(double amount) {
this.amount = amount;
}
double processPayment() {
return amount;
}
}
// -------- SUB CLASS : CREDIT CARD --------
class CreditCardPayment extends Payment {
CreditCardPayment(double amount) {
super(amount);
}
double processPayment() {
return amount + (amount * 0.02); // 2% service charge
}
}
// -------- SUB CLASS : UPI --------
class UPIPayment extends Payment {
UPIPayment(double amount) {
super(amount);
}
double processPayment() {
return amount + 5; // Flat ₹5 charge
}
}
// -------- SUB CLASS : NET BANKING --------
class NetBankingPayment extends Payment {
NetBankingPayment(double amount) {
super(amount);
}
double processPayment() {
return amount + (amount * 0.015); // 1.5% service charge
}
}
// -------- MAIN CLASS --------
public class OnlinePaymentSystem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter payment amount: ");
double amount = sc.nextDouble();
System.out.println("\nChoose Payment Method:");
System.out.println("1. Credit Card");
System.out.println("2. UPI");
System.out.println("3. Net Banking");
System.out.print("Enter choice: ");
int choice = sc.nextInt();
Payment payment; // Base class reference
switch (choice) {
case 1:
payment = new CreditCardPayment(amount);
break;
case 2:
payment = new UPIPayment(amount);
break;
case 3:
payment = new NetBankingPayment(amount);
break;
default:
System.out.println("Invalid choice");
sc.close();
return;
}
// Dynamic method dispatch
double finalAmount = payment.processPayment();
System.out.println("\nFinal Payable Amount: ₹" + finalAmount);
sc.close();
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+97
View File
@@ -0,0 +1,97 @@
// -------- Shared Buffer Class --------
class Buffer {
private int value;
private boolean hasValue = false;
// Producer puts value
synchronized void put(int value) {
while (hasValue) {
try {
wait(); // wait if buffer is full
} catch (InterruptedException e) {
System.out.println(e);
}
}
this.value = value;
hasValue = true;
System.out.println("Produced: " + value);
notify(); // notify consumer
}
// Consumer gets value
synchronized int get() {
while (!hasValue) {
try {
wait(); // wait if buffer is empty
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Consumed: " + value);
hasValue = false;
notify(); // notify producer
return value;
}
}
// -------- Producer Thread --------
class Producer extends Thread {
Buffer buffer;
Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
int i = 1;
while (true) {
buffer.put(i++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// -------- Consumer Thread --------
class Consumer extends Thread {
Buffer buffer;
Consumer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
while (true) {
buffer.get();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// -------- Main Class --------
public class ProducerConsumerDemo {
public static void main(String[] args) {
Buffer buffer = new Buffer();
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
producer.start();
consumer.start();
}
}
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+107
View File
@@ -0,0 +1,107 @@
import java.util.Scanner;
// -------- Interface for Circle --------
interface CircleOps {
double circleArea();
double circlePerimeter();
}
// -------- Interface for Rectangle --------
interface RectangleOps {
double rectangleArea();
double rectanglePerimeter();
}
// -------- Interface inheriting both --------
interface ShapeOps extends CircleOps, RectangleOps {
void displaySummary();
}
// -------- Base class --------
class ShapeBase {
double radius;
double length;
double breadth;
}
// -------- Implementing class --------
class ShapeCalculator extends ShapeBase implements ShapeOps {
ShapeCalculator(double radius, double length, double breadth) {
this.radius = radius;
this.length = length;
this.breadth = breadth;
}
// Circle operations
public double circleArea() {
return Math.PI * radius * radius;
}
public double circlePerimeter() {
return 2 * Math.PI * radius;
}
// Rectangle operations
public double rectangleArea() {
return length * breadth;
}
public double rectanglePerimeter() {
return 2 * (length + breadth);
}
// Summary method
public void displaySummary() {
System.out.println("\n--- Shape Summary ---");
System.out.println("Circle Area: " + circleArea());
System.out.println("Circle Perimeter: " + circlePerimeter());
System.out.println("Rectangle Area: " + rectangleArea());
System.out.println("Rectangle Perimeter: " + rectanglePerimeter());
}
}
// -------- Demo class --------
public class ShapesDemo {
// Method accepting CircleOps
static void circleOperations(CircleOps c) {
System.out.println("\nCircle Area: " + c.circleArea());
System.out.println("Circle Perimeter: " + c.circlePerimeter());
}
// Method accepting RectangleOps
static void rectangleOperations(RectangleOps r) {
System.out.println("\nRectangle Area: " + r.rectangleArea());
System.out.println("Rectangle Perimeter: " + r.rectanglePerimeter());
}
// Method accepting ShapeOps
static void shapeOperations(ShapeOps s) {
s.displaySummary();
}
// -------- Main method --------
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius of circle: ");
double radius = sc.nextDouble();
System.out.print("Enter length of rectangle: ");
double length = sc.nextDouble();
System.out.print("Enter breadth of rectangle: ");
double breadth = sc.nextDouble();
ShapeCalculator shape = new ShapeCalculator(radius, length, breadth);
// Polymorphism using interface references
circleOperations(shape);
rectangleOperations(shape);
shapeOperations(shape);
sc.close();
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+121
View File
@@ -0,0 +1,121 @@
import java.util.Scanner;
// -------- Helper Class --------
class TextHelper {
private String text;
private String keyword;
TextHelper(String text, String keyword) {
this.text = text;
this.keyword = keyword;
}
// 1. View character at a position
void viewCharacter(int position) {
if (position >= 0 && position < text.length()) {
System.out.println(
"Character at position " +
position +
": " +
text.charAt(position)
);
} else {
System.out.println("Invalid position!");
}
}
// 2. Compare text and keyword
void compareText() {
int result = text.compareTo(keyword);
if (result == 0) System.out.println("Text and keyword are equal.");
else if (result < 0) System.out.println(
"Text comes before keyword alphabetically."
);
else System.out.println("Keyword comes before text alphabetically.");
}
// 3. Search & replace keyword
void searchAndReplace(String replacement) {
int index = text.indexOf(keyword);
if (index == -1) {
System.out.println("Keyword not found in text.");
} else {
System.out.println("Keyword first found at position: " + index);
text = text.replace(keyword, replacement);
System.out.println("Updated Text: " + text);
}
}
// 4. Extract substring
void extractPortion(int start, int end) {
if (start >= 0 && end <= text.length() && start < end) {
System.out.println("Extracted Text: " + text.substring(start, end));
} else {
System.out.println("Invalid start or end position!");
}
}
}
// -------- Main Class --------
public class TextProcessingHelper {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter main text: ");
String text = sc.nextLine();
System.out.print("Enter keyword: ");
String keyword = sc.nextLine();
TextHelper helper = new TextHelper(text, keyword);
int choice;
do {
System.out.println("\n--- Text Processing Menu ---");
System.out.println("1. View character at a position");
System.out.println("2. Compare text and keyword");
System.out.println("3. Search and replace keyword");
System.out.println("4. Extract portion of text");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
sc.nextLine(); // consume newline
switch (choice) {
case 1:
System.out.print("Enter position: ");
int pos = sc.nextInt();
helper.viewCharacter(pos);
break;
case 2:
helper.compareText();
break;
case 3:
System.out.print("Enter replacement word: ");
String replacement = sc.nextLine();
helper.searchAndReplace(replacement);
break;
case 4:
System.out.print("Enter start position: ");
int start = sc.nextInt();
System.out.print("Enter end position: ");
int end = sc.nextInt();
helper.extractPortion(start, end);
break;
case 5:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 5);
sc.close();
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+65
View File
@@ -0,0 +1,65 @@
import java.util.Scanner;
class Student {
private int m1, m2, m3;
// Static counter to track enrolled students
static int studentCount = 0;
// Static block to display welcome message
static {
System.out.println("Welcome to University Enrollment System");
}
// Constructor
Student(int m1, int m2, int m3) {
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
studentCount++;
}
// Non-static method to compute average of best two marks
void displayAverage() {
int bestTwoSum = m1 + m2 + m3 - Math.min(m1, Math.min(m2, m3));
double average = bestTwoSum / 2.0;
System.out.println("Average of best two marks: " + average);
}
// Static method to display total enrolled students
static void displayTotalStudents() {
System.out.println("Total students enrolled: " + studentCount);
}
}
public class UniversityEnrollment {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students to enroll: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.println("\nEnter marks for Student " + i);
System.out.print("Mark 1: ");
int m1 = sc.nextInt();
System.out.print("Mark 2: ");
int m2 = sc.nextInt();
System.out.print("Mark 3: ");
int m3 = sc.nextInt();
Student s = new Student(m1, m2, m3);
s.displayAverage();
}
// Display total enrolled students
Student.displayTotalStudents();
sc.close();
}
}
Binary file not shown.
+53
View File
@@ -0,0 +1,53 @@
class MyPoint {
private int x;
private int y;
// No-argument constructor
MyPoint() {
x = 0;
y = 0;
}
// Overloaded constructor
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
// Set both x and y
void setXY(int x, int y) {
this.x = x;
this.y = y;
}
// Return x and y as a 2-element array
int[] getXY() {
return new int[] { x, y };
}
// String representation
public String toString() {
return "(" + x + ", " + y + ")";
}
// Distance to given (x, y)
double distance(int x, int y) {
return Math.sqrt(
(this.x - x) * (this.x - x) + (this.y - y) * (this.y - y)
);
}
// Distance to another MyPoint object
double distance(MyPoint another) {
return Math.sqrt(
(this.x - another.x) * (this.x - another.x) +
(this.y - another.y) * (this.y - another.y)
);
}
// Distance to origin (0, 0)
double distance() {
return Math.sqrt(x * x + y * y);
}
}
Binary file not shown.
+57
View File
@@ -0,0 +1,57 @@
import java.util.Scanner;
public class TestMyPoint {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Test default constructor
MyPoint p1 = new MyPoint();
System.out.println("p1: " + p1);
// Test overloaded constructor
System.out.print("Enter x coordinate: ");
int x = sc.nextInt();
System.out.print("Enter y coordinate: ");
int y = sc.nextInt();
MyPoint p2 = new MyPoint(x, y);
System.out.println("p2: " + p2);
// Test setXY()
System.out.print("Enter new x for p1: ");
int x1 = sc.nextInt();
System.out.print("Enter new y for p1: ");
int y1 = sc.nextInt();
p1.setXY(x1, y1);
System.out.println("Updated p1: " + p1);
// Test getXY()
int[] coords = p1.getXY();
System.out.println("getXY(): (" + coords[0] + ", " + coords[1] + ")");
// Test distance() to origin
System.out.println("Distance from p1 to origin: " + p1.distance());
// Test distance(int x, int y)
System.out.print("Enter x of another point: ");
int x2 = sc.nextInt();
System.out.print("Enter y of another point: ");
int y2 = sc.nextInt();
System.out.println(
"Distance from p1 to (" +
x2 +
", " +
y2 +
"): " +
p1.distance(x2, y2)
);
// Test distance(MyPoint another)
System.out.println("Distance from p1 to p2: " + p1.distance(p2));
sc.close();
}
}