0% found this document useful (0 votes)
2 views41 pages

Java Lab Record

The document outlines the Java Programming Practices Lab Record Manual for the Anil Neerukonda Institute of Technology & Sciences, detailing course objectives, outcomes, and various programming assignments. It includes examples of Java programs for managing bank accounts, checking prime palindromes, calculating marks, and designing a farm animal application, among others. The manual serves as a guide for students to understand object-oriented programming concepts and apply them in practical scenarios.

Uploaded by

RAHUL SADARAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views41 pages

Java Lab Record

The document outlines the Java Programming Practices Lab Record Manual for the Anil Neerukonda Institute of Technology & Sciences, detailing course objectives, outcomes, and various programming assignments. It includes examples of Java programs for managing bank accounts, checking prime palindromes, calculating marks, and designing a farm animal application, among others. The manual serves as a guide for students to understand object-oriented programming concepts and apply them in practical scenarios.

Uploaded by

RAHUL SADARAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

1

Anil Neerukonda Institute of Technology & Sciences


(Autonomous)
(Permanent Affiliation by Andhra University & Approved by AICTE
Accredited by NBA (ECE, EEE, CSE, IT, Mech. Civil & Chemical) &
NAAC)
Sangivalasa-531 162, Bheemunipatnam Mandal, Visakhapatnam
District

Regulation R23

DEPARTMENT OF CSE (Data Science)

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


2

JAVA PROGRAMMING PRACTICES LAB RECORD MANUAL


Course Code : 23CD9201 Credits : 2.5
Instruction : 1 L+1 T + 3 P / Week Sessional Marks : 50
End Exam : 3 Hours End Exam Marks : 50

Prerequisites:

• Basic knowledge of computer fundamentals.


• Student must have knowledge of some programming languages (such as C, C++)
Course Objectives:

• To Understand Object Oriented Programming Concepts and Apply Them in Problem


Solving.
• To Learn The Basics of Java Console and GUI Based Programming.
Course Outcomes:

By the end of the course, the student will be able to:


1 Develop classes for real time applications and establish the connectivity among the
classes using inheritance and usage of strings.
2 Modularize the application using packages, Interfaces and use of file concepts
3 Apply threads on classes to achieve parallelism through synchronization and
develop test cases by including the runtime errors using exceptions handling
mechanism
4 Solve the complex problems using collection framework.
5

Mapping of course outcomes with program outcomes:

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


3

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;

// Method to set account details


void setDetails(String accNo, String accType, double bal, double rate,
double limit)
{
accountNumber = accNo;
accountType = accType;
balance = bal;
interestRate = rate;
overdraftLimit = limit;
}
// Deposit method
void deposit(double amount)
{
balance += amount;
System.out.println("Deposited" + amount + "New Balance:" + balance);
}
// Withdraw method
void withdraw(double amount) {
if (accountType.equals("Current")) {

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


4

if ((balance + overdraftLimit) >= amount) {


balance -= amount;
System.out.println("Withdrew " + amount + "New Balance:" + balance);
}
else {
System.out.println("Overdraft limit exceeded!");
}
}
else {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrew " + amount + "New Balance: ₹" +
balance);
}
else {
System.out.println("Insufficient balance!");
}
}
}

// Calculate interest (only for Savings)


void calculateInterest() {
if (accountType.equals("Savings")) {
double interest = balance * interestRate;
System.out.println("Interest:" + interest);
}
else {
System.out.println("No interest for current account.");
}
}
// Transfer to another account
void transfer(double amount, Account receiver)
{
if (balance >= amount)
{
balance -= amount;
receiver.balance += amount;
System.out.println("Transferred" + amount + "to" +
receiver.accountNumber);
}
else
{
System.out.println("Transfer failed: Insufficient balance.");

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


5

}
}

// Display account details


void display() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Type: " + accountType);
System.out.println("Balance: ₹" + balance);
}
}

//Bank details class


class BankAccountManagementSystem
{
public static void main(String[] args)
{
// Create two accounts
Account acc1 = new Account();
Account acc2 = new Account();

// Set account details manually


acc1.setDetails("S123", "Savings", 5000, 0.04, 0);
acc2.setDetails("C456", "Current", 2000, 0.0, 5000);

// Perform transactions
System.out.println("\n--- Savings Account ---");
acc1.deposit(1000);
acc1.withdraw(2000);
acc1.calculateInterest();
acc1.display();

System.out.println("\n--- Current Account ---");

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();
}}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


6

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

--- Current Account ---


Deposited1000.0New Balance:3000.0
Withdrew 4000.0New Balance:-1000.0
No interest for current account.
Account Number: C456
Account Type: Current
Balance: ?-1000.0

--- Transfer from Savings to Current ---


Transferred1000.0toC456

--- Final Balances ---


Account Number: S123
Account Type: Savings
Balance: ?3000.0
Account Number: C456
Account Type: Current
Balance: 0.0

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


7

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;
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


8

// 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);

if (prime && palindrome) {


System.out.println(number + " is a Prime Palindrome.");
} else if (prime) {
System.out.println(number + " is Prime but not a Palindrome.");
} else if (palindrome) {
System.out.println(number + " is a Palindrome but not Prime.");
} else {
System.out.println(number + " is neither Prime nor Palindrome.");
}
sc.close();
}
}

OUTPUT:
Javac PrimePalindromeCheck
Java PrimePalindromeCheck
Enter a number: 131
131 is a Prime Palindrome.

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


9

2. Write a java program which reads marks of five subjects through


command line and print the total and average.

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

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


10

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("-----------------------");
}
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


11

public class FarmAnimals {


public static void main(String[] args) {
Animal cow = new Animal();
Animal pig = new Animal();
Animal horse = new Animal();
cow.setDetails("Cow", "Cowshed", "Grass and Hay", "Moo");
pig.setDetails("Pig", "Pigsty", "Vegetable Scraps", "Oink");
horse.setDetails("Horse", "Stable", "Hay and Grains", "Neigh");
cow.displayDetails();
pig.displayDetails();
horse.displayDetails();
}
}
OUTPUT :
Animal: Cow
Stays in: Cowshed
Eats: Grass and Hay
Sound: Moo

Animal: Pig
Stays in: Pigsty
Eats: Vegetable Scraps
Sound: Oink

Animal: Horse
Stays in: Stable
Eats: Hay and Grains
Sound: Neigh

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


12

4. Write a Java Program to below class diagram:

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() {

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


13

System.out.println("Normal order received.");


}
}
// Customer class
class Customer {
String name;
String location;
void sendOrder() {
System.out.println("Order sent by customer.");
}
void receiveOrder() {
System.out.println("Order received by customer.");
}
}
// Main class to test the code
public class Main {
public static void main(String[] args) {
// Create a customer
Customer customer = new Customer();
customer.name = "John Doe";
customer.location = "New York";
customer.sendOrder();

// Create and test SpecialOrder


SpecialOrder spOrder = new SpecialOrder();
spOrder.date = "2025-06-16";
spOrder.number = "SP001";

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


14

spOrder.confirm();
spOrder.dispatch();
spOrder.close();

// Create and test NormalOrder


NormalOrder nmOrder = new NormalOrder();
nmOrder.date = "2025-06-17";
nmOrder.number = "NM001";
nmOrder.confirm();
nmOrder.dispatch();
nmOrder.receive();
nmOrder.close();
customer.receiveOrder();
}
}

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.

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


15

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 1: Only name and ID


Employee(String name, int id) {
this.name = name;
this.id = id;
this.designation = "Not Assigned";
this.salary = 0.0;
this.promotionStatus = "Not Evaluated";
}
// Constructor 2: Name, ID, and designation
Employee(String name, int id, String designation) {
this.name = name;
this.id = id;
this.designation = designation;
this.salary = 0.0;
this.promotionStatus = "Not Evaluated";

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


16

}
// 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

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


17

Employee emp3 = new Employee("Charlie", 103, "Manager", 75000.0,


"Eligible");
// Display all employees
emp1.display();
emp2.display();
emp3.display();
}
}
OUTPUT :
Name: Alice
ID: 101
Designation: Not Assigned
Salary: ₹0.0
Promotion Status: Not Evaluated

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

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


18

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);
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


19

// Update the map with current character index


seen.put(currentChar, end);

// Update max length and substring if found longer


if (end - start + 1 > maxLength) {
maxLength = end - start + 1;
longestSubstring = s.substring(start, end + 1);
}
}
System.out.println("Length: " + maxLength);
System.out.println("Longest Substring: " + longestSubstring);
}
}

OUTPUT :
Enter input string: abcabcbb
Length: 3
Longest Substring: abc

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


20

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.

Write a JAVA program to implement bank functionality in the above


scenario and demonstrate the dynamic polymorphism concept. Note:
Create few classes namely Customer, Account, RBI (Base Class) and few
derived classes (SBI, ICICI, PNB etc). Assume and implement required
member variables and functions in each class.

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
}
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


21

// Derived class - SBI


class SBI extends RBI {
public double getInterestRate() {
return 7.0;
}
}
// Derived class - ICICI
class ICICI extends RBI {
public double getInterestRate() {
return 6.5;
}
}

// Derived class - PNB


class PNB extends RBI {
public double getInterestRate() {
return 6.0;
}
}

// 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();

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


22

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%

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


23

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.

Find the monthly salary details of Employee.


If input is Regular Employee display the Regular employee salary details.
If input is Contract based display the Contract salary details.

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 {

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


24

int basic = 25000;


int hra = 15000;
int ta = 5000;
int total;

public void calculateSalary() {


total = basic + hra + ta;
}

public void displayDetails() {


System.out.println("Salary Details:");
System.out.println("Basic Pay: " + basic);
System.out.println("HRA: " + hra);
System.out.println("T.A: " + ta);
System.out.println("Total Amount: " + total);
}
}

// Contract Employee implementation


class ContractEmployee implements Salary {
int basic = 12000;
int ta = 3000;
int total;
public void calculateSalary() {
total = basic + ta;
}
public void displayDetails() {

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


25

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 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter Employee ID: ");


String empId = sc.nextLine();
Salary emp = null;
System.out.print("Enter Employee Type (Regular/Contract): ");
String empType = sc.nextLine();

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;
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


26

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

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


27

WEEK – 9
9. Define a package number and in that define Roman class and implement
romanToInteger() and import the method in another class.

Input: "LVIII" Output: 58


Explanation: L = 50, V= 5, III = 3.
PROCESS
Step1 : create package by name number OR Folder by name number
Step2 : create Roman.java file in that package OR folder
Step 3: compile Roman.java
javac Roman.java
Step 3: create Romanmain.java file outside of the package
Step 4: javac Romanmain.java
Step 4: java Romanmain.java

//ROMAN.JAVA

package number;
import java.util.HashMap;

public class Roman {


public int romanToInteger(String s) {
HashMap<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);

int total = 0;
int prevValue = 0;

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


28

for (int i = s.length() - 1; i >= 0; i--) {


int curr = map.get(s.charAt(i));

if (curr < prevValue) {


total -= curr;
} else {
total += curr;
}
prevValue = curr;
}

return total;
}
}

//ROMANMAIN.JAVA
import number.Roman; // Importing Roman class from 'number' package
import java.util.Scanner;

public class RomanMain {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Roman numeral: ");
String romanInput = sc.nextLine().toUpperCase();
Roman romanConverter = new Roman();
int result = romanConverter.romanToInteger(romanInput);

System.out.println("Integer value: " + result);


}
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


29

OUTPUT :
Enter Roman numeral: LVIII
Integer value: 58

WEEK – 10

10. File Handling :


Write the below text in the file called sample.txt and then find the
frequency count of the patterns ‗pe‘, and ‗pi‘ Peter Piper picked a peck of
pickled peppers A peck of pickled peppers Peter Piper picked If Peter Piper
picked a peck of pickled peppers Where‘s the peck of pickled peppers Peter
Piper picked?

Expected Output:
‗pe‘ – no of occurrences - 20
‗pi‘ – no of occurrences – 12
PROGRAM :
import java.io.*;
import java.util.regex.*;

public class PatternFrequencyCounter {


public static void main(String[] args) {
String fileName = "sample.txt";
String content = "Peter Piper picked a peck of pickled peppersA peck of
pickled peppersPeter Piper pickedIf Peter Piper picked a peck of pickled
peppersWhere‘s the peck of pickled peppers Peter Piper picked?";

// Step 1: Write content to file

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


30

try (BufferedWriter writer = new BufferedWriter(new


FileWriter(fileName))) {
writer.write(content);
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
return;
}
// Step 2: Read content from file and count "pe" and "pi"
int peCount = 0;
int piCount = 0;

try (BufferedReader reader = new BufferedReader(new


FileReader(fileName))) {
String line;

while ((line = reader.readLine()) != null) {


peCount += countOccurrences(line.toLowerCase(), "pe");
piCount += countOccurrences(line.toLowerCase(), "pi");
}

} 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);
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


31

// Helper method to count overlapping occurrences


public static int countOccurrences(String line, String pattern) {
int count = 0;
for (int i = 0; i <= line.length() - pattern.length(); i++) {
if (line.substring(i, i + pattern.length()).equals(pattern)) {
count++;
}
}
return count;
}
}

OUTPUT :
'pe' - number of occurrences: 20
'pi' - number of occurrences: 12

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


32

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;

public class SimpleMobileNumberValidator {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Test cases
String[] inputs = {"9885089465", "98567890121", "88664433",
"98ab@123"};

for (String number : inputs) {


System.out.println("\nInput: " + number);
try {
if (!number.matches("[0-9]+")) {
throw new NumberFormatException("Invalid Mobile Number –
NumberFormatException");
} else if (number.length() > 10) {

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


33

throw new Exception("Invalid Mobile Number –


ArrayIndexOutofBounds Exception");
} else if (number.length() < 10) {
throw new Exception("Invalid Mobile Number –
LengthNotSufficientException");
} else {
System.out.println("Valid number");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
sc.close();
}
}

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

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


34

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);

if (requestedSeats <= totalSeats) {


System.out.println("Seat Available. Reserve now :-)");
totalSeats -= requestedSeats;
System.out.println(requestedSeats + " seats reserved.");
} else {
System.out.println("Requested seats not available :-)");
}
System.out.println(personName + " leaving.\n");
}
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


35

// Thread class for person trying to reserve

class Person extends Thread {


Reservation reservation;
String personName;
int seats;

Person(Reservation r, String name, int s) {


reservation = r;
personName = name;
seats = s;
}

public void run() {


reservation.reserve(personName, seats);
}
}

// Main class
public class ReservationSystem {
public static void main(String[] args) {
Reservation r = new Reservation();

// Creating person threads


Person p1 = new Person(r, "Person-1", 5);
Person p2 = new Person(r, "Person-2", 2);
Person p3 = new Person(r, "Person-3", 4);

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


36

// Starting the threads


p1.start();
p2.start();
p3.start();
}
}

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.

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


37

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;

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


38

backtrack(result, digits, 0, new StringBuilder());


return result;
}
// Backtracking function
private static void backtrack(List<String> result, String digits, int index,
StringBuilder current) {
if (index == digits.length()) {
result.add(current.toString());
return;
}
String letters = KEYPAD[digits.charAt(index) - '0'];
for (char c : letters.toCharArray()) {
current.append(c);
backtrack(result, digits, index + 1, current);
current.deleteCharAt(current.length() - 1); // Backtrack
}
}
public static void main(String[] args) {
String input = "23";
List<String> combinations = letterCombinations(input);
System.out.println("Input: " + input);
System.out.println("Output: " + combinations);
}
}

OUTPUT :
Input: 23
Output: [ad, ae, af, bd, be, bf, cd, ce, cf]

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


39

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();

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


40

if (!isMatching(top, ch)) {
return false; // Mismatched pair
}
}
}

// If stack is empty, all brackets matched


return stack.isEmpty();
}
// Helper method to match brackets
private static boolean isMatching(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
public static void main(String[] args) {
String input1 = "()";
String input2 = "({)}";
System.out.println("Input: " + input1);
System.out.println(isValid(input1) ? "Output: Valid" : "Output: Not Valid");
System.out.println("\nInput: " + input2);
System.out.println(isValid(input2) ? "Output: Valid" : "Output: Not Valid");
}
}

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026


41

OUTPUT :
Input: ()
Output: Valid

Input: ({)}
Output: Not Valid

Dr. ISSR, Asso. Professor 2-1-CSE(DS) 2025-2026

You might also like