Java Lab Record
Java Lab Record
Regulation R23
Prerequisites:
Week – 1,2
1. Sample Case study on class & objects
Bank Account Management System:
Problem Statement: Design a system to manage bank accounts. Classes:
Account, Savings-Account, Current-Account.
Attributes: Account number, balance, account type, interest rate (for
savings account), overdraft limit (for current account), etc. Methods:
Deposit, Withdraw, Calculate Interest, Transfer, etc. Object Usage: Create
objects for each customer's account and perform transactions like deposits,
withdrawals, and transfers.
PROGRAM :
//Account class
class Account {
String accountNumber;
String accountType;
double balance;
double interestRate;
double overdraftLimit;
}
}
// Perform transactions
System.out.println("\n--- Savings Account ---");
acc1.deposit(1000);
acc1.withdraw(2000);
acc1.calculateInterest();
acc1.display();
acc2.deposit(1000);
acc2.withdraw(4000); // should use overdraft
acc2.calculateInterest();
acc2.display();
System.out.println("\n--- Transfer from Savings to Current ---");
acc1.transfer(1000, acc2);
System.out.println("\n--- Final Balances ---");
acc1.display();
acc2.display();
}}
OUTPUT :
javac Banksimple.java
java Banksimple.java
--- Savings Account ---
Deposited1000.0New Balance:6000.0
Withdrew 2000.0New Balance: ?4000.0
Interest:160.0
Account Number: S123
Account Type: Savings
Balance: ?4000.0
WEEK – 3
1. Sample program to check whether the given number is prime
palindrome or not
PROGRAM :
import java.util.Scanner;
public class PrimePalindromeCheck {
// Method to check if a number is prime
static boolean isPrime(int num) {
if (num <= 1)
return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
return false;
}
return true;
}
// Method to check if a number is a palindrome
static boolean isPalindrome(int num) {
int original = num;
int reversed = 0;
while (num > 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return original == reversed;
}
// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
boolean prime = isPrime(number);
boolean palindrome = isPalindrome(number);
OUTPUT:
Javac PrimePalindromeCheck
Java PrimePalindromeCheck
Enter a number: 131
131 is a Prime Palindrome.
PROGRAM :
//CLASS MARKS CALCULATOR
public class MarksCalculator {
public static void main(String[] args) {
if (args.length != 5) {
System.out.println("Please enter marks for exactly 5 subjects.");
return;
}
int total = 0;
for (int i = 0; i < 5; i++) {
int mark = Integer.parseInt(args[i]);
total += mark;
}
double average = total / 5.0;
System.out.println("Total Marks = " + total);
System.out.println("Average Marks = " + average);
}
}
OUTPUT :
Javac MarksCalculator.java
java MarksCalculator 78 85 90 66 80
Total Marks = 399
Average Marks = 79.8
WEEK – 4,5
3. Design a farm animals java application with the details of animals like cow,
pig, horse. Consider the following details like where they stay, what they
eat, the sound they make by using classes and objects.
PROGRAM :
// File: FarmAnimals.java
class Animal {
String name;
String place;
String food;
String sound;
void setDetails(String n, String p, String f, String s) {
name = n;
place = p;
food = f;
sound = s;
}
void displayDetails() {
System.out.println("Animal: " + name);
System.out.println("Stays in: " + place);
System.out.println("Eats: " + food);
System.out.println("Sound: " + sound);
System.out.println("-----------------------");
}
}
Animal: Pig
Stays in: Pigsty
Eats: Vegetable Scraps
Sound: Oink
Animal: Horse
Stays in: Stable
Eats: Hay and Grains
Sound: Neigh
PROGRAM :
// Base Order class
class Order {
String date;
String number;
void confirm() {
System.out.println("Order confirmed.");
}
void close() {
System.out.println("Order closed.");
}
}
// SpecialOrder class inherits from Order
class SpecialOrder extends Order {
void dispatch() {
System.out.println("Special order dispatched.");
}
}
// NormalOrder class inherits from Order
class NormalOrder extends Order {
void dispatch() {
System.out.println("Normal order dispatched.");
}
void receive() {
spOrder.confirm();
spOrder.dispatch();
spOrder.close();
OUTPUT :
Order sent by customer.
Order confirmed.
Special order dispatched.
Order closed.
Order confirmed.
Normal order dispatched.
Normal order received.
Order closed.
Order received by customer.
5. Constructor overloading :
An organization is maintaining the data of employee according to cadre of
employee with following parameters: name, id, designation, salary,
promotion status. Apply the constructor overloading to implement it.
PROGRAM :
class Employee {
String name;
int id;
String designation;
double salary;
String promotionStatus;
}
// Constructor 3: All details
Employee(String name, int id, String designation, double salary, String
promotionStatus) {
this.name = name;
this.id = id;
this.designation = designation;
this.salary = salary;
this.promotionStatus = promotionStatus;
}
// Method to display employee details
void display() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Designation: " + designation);
System.out.println("Salary: ₹" + salary);
System.out.println("Promotion Status: " + promotionStatus);
System.out.println("----------------------------");
}
}
class EmployeeMain {
public static void main(String[] args) {
// Using constructor 1
Employee emp1 = new Employee("Alice", 101);
// Using constructor 2
Employee emp2 = new Employee("Bob", 102, "Junior Developer");
// Using constructor 3
Name: Bob
ID: 102
Designation: Junior Developer
Salary: ₹0.0
Promotion Status: Not Evaluated
Name: Charlie
ID: 103
Designation: Manager
Salary: ₹75000.0
Promotion Status: Eligible
WEEK - 6
6. Strings:
Write a program to find the longest Substring without Repeating Characters
Input: abcabcbb output:3 string: abc Input: pwwkew output:3 string: wke
Note: pwke is not a substring , it is a subsequence
PROGRAM :
import java.util.*;
public class LongestUniqueSubstring {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter input string: ");
String s = sc.nextLine();
int maxLength = 0;
int start = 0;
String longestSubstring = "";
Map<Character, Integer> seen = new HashMap<>();
for (int end = 0; end < s.length(); end++) {
char currentChar = s.charAt(end);
// If character is repeated, update the start
if (seen.containsKey(currentChar)) {
start = Math.max(seen.get(currentChar) + 1, start);
}
OUTPUT :
Enter input string: abcabcbb
Length: 3
Longest Substring: abc
WEEK – 7
7. Method overriding:
All the banks operating in India are controlled by RBI. (e.g. minimum
interest rate, minimum balance allowed, maximum withdrawal limit etc)
which all banks must follow. For example, suppose RBI has set minimum
interest rate applicable to a saving bank account to be 4% annually.
however, banks are free to use 4% interest rate or to set any rates above it.
Testcase1:
Enter the Bank name to find the rate of Interest : RBI RBI rate of interest
is : 4%
Testcase2:
Enter the Bank name to find the rate of Interest : SBI RBI rate of interest
is : 7%
PROGRAM :
import java.util.Scanner;
// Base class
class RBI {
public double getInterestRate() {
return 4.0; // Minimum interest rate
}
}
// Main class
public class BankInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Bank name to find the rate of Interest: ");
String bankName = sc.nextLine().trim().toUpperCase();
RBI bank;
switch (bankName) {
case "SBI":
bank = new SBI();
break;
case "ICICI":
bank = new ICICI();
break;
case "PNB":
bank = new PNB();
break;
case "RBI":
bank = new RBI();
break;
default:
System.out.println("Bank not recognized.");
return;
}
System.out.println(bankName + " rate of interest is: " +
bank.getInterestRate() + "%");
}
}
OUTPUT :
Enter the Bank name to find the rate of Interest: RBI
RBI rate of interest is: 4.0%
WEEK – 8
8. Interfaces:
Different categories of employees are working in a software company like
Regular Employees, Contract Employees and Vendors. And their pay roll
is different for regular and contract employees.
For the regular employees : Basic pay is 25000, HRA is 15000rs and TA is
5000.
For the Contract employees Basic pay is 12000 TA is 3000rs and there is
no HRA.
TestCase1:
Input:
Enter Employee Id: R101
Output:
Salary Details:
Basic Pay: 25000 HRA: 15000 T.A: 5000 Total Amount: 45000
PROGRAM :
import java.util.Scanner;
// Interface for salary
interface Salary {
void calculateSalary();
void displayDetails();
}
// Regular Employee implementation
class RegularEmployee implements Salary {
System.out.println("Salary Details:");
System.out.println("Basic Pay: " + basic);
System.out.println("T.A: " + ta);
System.out.println("Total Amount: " + total);
}
}
// Main class to run the program
public class EmployeeSalarySystem {
if (empType.equalsIgnoreCase("Regular")) {
emp = new RegularEmployee();
} else if (empType.equalsIgnoreCase("Contract")) {
emp = new ContractEmployee();
} else {
System.out.println("Invalid Employee Type!");
sc.close();
return;
}
emp.calculateSalary();
emp.displayDetails();
}
}
OUTPUT :
Enter Employee ID: 101
Enter Employee Type (Regular/Contract): Regular
Salary Details:
Basic Pay: 25000
HRA: 15000
T.A: 5000
Total Amount: 45000
WEEK – 9
9. Define a package number and in that define Roman class and implement
romanToInteger() and import the method in another class.
//ROMAN.JAVA
package number;
import java.util.HashMap;
int total = 0;
int prevValue = 0;
return total;
}
}
//ROMANMAIN.JAVA
import number.Roman; // Importing Roman class from 'number' package
import java.util.Scanner;
OUTPUT :
Enter Roman numeral: LVIII
Integer value: 58
WEEK – 10
Expected Output:
‗pe‘ – no of occurrences - 20
‗pi‘ – no of occurrences – 12
PROGRAM :
import java.io.*;
import java.util.regex.*;
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
return;
}
// Output results
System.out.println("'pe' - number of occurrences: " + peCount);
System.out.println("'pi' - number of occurrences: " + piCount);
}
OUTPUT :
'pe' - number of occurrences: 20
'pi' - number of occurrences: 12
WEEK – 11
11. Exception Handling Input a mobile number and check the given
number is valid mobile number or not.
• A valid mobile number is a combination of (0-9) digits of length
exactly 10.
• If the given Number Exceeds length of 10 raise Invalid Mobile
Number- ArrayIndexOutofBounds Exception
• If the given Number less than the length of 10 raise Invalid Mobile
Number – LengthNotSufficientException
• If the given Number contain any character other than digit raise
Invalid Mobile Number –NumberFormatException Sample Input
9885089465 98567890121 88664433 98ab@123
• Expected Output – 1 Valid number Invalid Mobile Number-
ArrayIndexOutofBounds Exception Invalid Mobile Number –
LengthNotSufficientException Invalid Mobile Number –
NumberFormatException
PROGRAM :
import java.util.Scanner;
// Test cases
String[] inputs = {"9885089465", "98567890121", "88664433",
"98ab@123"};
OUTPUT :
String[] inputs = {"9885089465", "98567890121", "88664433", "98ab@123"};
Input: 9885089465
Valid number
Input: 98567890121
Invalid Mobile Number – ArrayIndexOutofBounds Exception
Input: 88664433
Invalid Mobile Number – LengthNotSufficientException
Input: 98ab@123
Invalid Mobile Number – NumberFormatException
WEEK - 12
12. Multi-Threading:
Implement a Reservation system which allows the persons to book seats.
Define reserve method initially with 100 seats. Now create one or more
person threads to book seats. At any time it should allow only one person
thread to access the reserve method.
PROGRAM :
// Reservation class with synchronized reserve method
class Reservation {
int totalSeats = 10;
synchronized void reserve(String personName, int requestedSeats) {
System.out.println(personName + " entered.");
System.out.println("Available seats: " + totalSeats + " Requested seats: " +
requestedSeats);
// Main class
public class ReservationSystem {
public static void main(String[] args) {
Reservation r = new Reservation();
OUTPUT :
Person-1 entered.
Available seats: 10 Requested seats: 5
Seat Available. Reserve now :-)
5 seats reserved.
Person-1 leaving.
Person-2 entered.
Available seats: 5 Requested seats: 2
Seat Available. Reserve now :-)
2 seats reserved.
Person-2 leaving.
Person-3 entered.
Available seats: 3 Requested seats: 4
Requested seats not available :-)
Person-3 leaving.
WEEK -13
13. Letter Combinations of a Phone Number :
Given a string containing digits from 2-9 inclusive, return all possible letter
combinations that the number could represent. A mapping of digit to letters
(just like on the telephone buttons) is given below. Note that 1 does not
map to any letters.
PROGRAM :
import java.util.*;
public class PhoneLetterCombinations {
// Mapping digits to letters like on a phone keypad
static final String[] KEYPAD = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz" // 9
};
// Main function to return all combinations
public static List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.length() == 0)
return result;
OUTPUT :
Input: 23
Output: [ad, ae, af, bd, be, bf, cd, ce, cf]
WEEK – 14
14. Arrays Write a program to find the Valid Parentheses:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid. An input string is valid if: 1. Open
brackets must be closed by the same type of brackets. 2. Open brackets
must be closed in the correct order.
Note that an empty string is also considered valid.
• Input: ( )
o Output:
o valid
• Input: ( { ) }
o Output: Not valid
PROGRAM :
import java.util.Stack;
public class ValidParentheses {
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
// Loop through each character
for (char ch : s.toCharArray()) {
// Push open brackets to stack
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
// If it's a closing bracket
else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) {
return false; // No matching open bracket
}
char top = stack.pop();
if (!isMatching(top, ch)) {
return false; // Mismatched pair
}
}
}
OUTPUT :
Input: ()
Output: Valid
Input: ({)}
Output: Not Valid