0% found this document useful (0 votes)
226 views101 pages

Java OOP Library Management System

The document describes a program to create a class hierarchy for representing library items using inheritance. It includes: 1) A base LibraryItem class with title and ID attributes 2) Book and DVD classes derived from LibraryItem, each adding author/director attributes 3) Constructors for each class and a displayInfo() method to output item details 4) A test program creating Book and DVD instances and calling displayInfo() The program implements a class hierarchy with a base LibraryItem class and derived Book and DVD classes to model different library item types using inheritance. It includes constructors, display methods, and a test program demonstrating the functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
226 views101 pages

Java OOP Library Management System

The document describes a program to create a class hierarchy for representing library items using inheritance. It includes: 1) A base LibraryItem class with title and ID attributes 2) Book and DVD classes derived from LibraryItem, each adding author/director attributes 3) Constructors for each class and a displayInfo() method to output item details 4) A test program creating Book and DVD instances and calling displayInfo() The program implements a class hierarchy with a base LibraryItem class and derived Book and DVD classes to model different library item types using inheritance. It includes constructors, display methods, and a test program demonstrating the functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OOPS LAB EXAM

1 . You are tasked with designing a simple application for managing a


library. The library has different types of items such as books and
DVDs. Your task is to create a class hierarchy using inheritance to
represent these items in the library. Requirements: Create a base class
named LibraryItem with the following attributes:
title (String): the title of the library item , itemID (int): a unique
identifier for each library item
Derive two classes from LibraryItem: 1)Book: represents a book in
the library. Include an additional attribute author (String) for the
book's author.
2) DVD: represents a DVD in the library. Include an additional
attribute director (String) for the DVD's director.
Implement appropriate constructors for each class.
Create a method in the LibraryItem class called displayInfo()
that displays the information about the library item (title, itemID).
Override the displayInfo() method in the Book and DVD classes to
include information specific to each type of item.
Create a test program to demonstrate the functionality of your
classes. In the test program, create instances of the Book and DVD
classes, and call the displayInfo() method to display their information.
Note: Ensure that the itemID is assigned automatically in a sequential
manner for each new library item created.
Sample output:
Book Information:
Title: Java language
Item ID: 1
Author: ABC
Type: BOOK

DVD Information:
Title: C language
Item ID:2
Author: Jack sparrow
Type: DVD

DVD Information:
Title: OOP
Item ID:3
Author: Black smith
Type: DVD

CODE:-

package adsf;
class LibraryItem {
private static int nextItemID = 1;

String title;
int itemID;

public LibraryItem(String title) {


[Link] = title;
[Link] = nextItemID++;
}

public void displayInfo() {


[Link]("Title: " + title);
[Link]("Item ID: " + itemID);
}
}

class Book extends LibraryItem {


String author;

public Book(String title, String author) {


super(title);
[Link] = author;
}

@Override
public void displayInfo() {
[Link]();
[Link]("Author: " + author);
[Link]("Type: BOOK\n");
}
}

class DVD extends LibraryItem {


String director;

public DVD(String title, String director) {


super(title);
[Link] = director;
}
@Override
public void displayInfo() {
[Link]();
[Link]("Director: " + director);
[Link]("Type: DVD\n");
}
}

public class LibraryTest {


public static void main(String[] args) {
// Test instances
Book book = new Book("Java language", "ABC");
DVD dvd1 = new DVD("C language", "Jack sparrow");
DVD dvd2 = new DVD("OOP", "Black smith");

// Display information
[Link]("Book Information:");
[Link]();

[Link]("DVD Information:");
[Link]();

[Link]("DVD Information:");
[Link]();
}
}

2.
Write a java program that includes functionalities such as
1) input string,
2) Displaying the length,
3) Finding and displaying the uppercase and lowercase versions,
4) Checking if the string is a palindrome,
5) Counting the occurrences of a specific character. and 6) string
concatenation.

package adsf;

import [Link];

public class StringManipulation {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// 1) Input String
[Link]("Enter a string: ");
String inputString = [Link]();
// 2) Displaying the length
[Link]("Length of the string: " +
[Link]());

// 3) Finding and displaying the uppercase and lowercase


versions
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());

// 4) Checking if the string is a palindrome


if (isPalindrome(inputString)) {
[Link]("The string is a palindrome.");
} else {
[Link]("The string is not a palindrome.");
}

// 5) Counting the occurrences of a specific character


[Link]("Enter a character to count: ");
char charToCount = [Link]().charAt(0);
int charCount = countOccurrences(inputString, charToCount);
[Link]("Occurrences of '" + charToCount + "': " +
charCount);

// 6) String concatenation
[Link]("Enter another string to concatenate: ");
String secondString = [Link]();
String concatenatedString = [Link](secondString);
[Link]("Concatenated string: " +
concatenatedString);

[Link]();
}

// Function to check if a string is a palindrome


private static boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return [Link](reversed);
}

// Function to count occurrences of a specific character in a string


public static int countOccurrences(String str, char specificChar) {
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == specificChar) {
count++;
}
}
return count;
}
}

3. A Java program that performs various operations on arrays. Your


program should include the following functionalities:
Input: Prompt the user to enter the size of an array. Allow the user to
input the elements of the array. Display: Display the entered array.
1) Find and Display: Find and display the sum of all elements in the
array.
2) Find and display the average of the elements.
3) Find and display the maximum and minimum values in the array.
4) Search: Prompt the user to enter a value to search for in the array.
Display whether the value is present in the array and, if yes, display
its index.

package adsf;
import [Link];

public class ArrayOperations {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

// Input: Prompt the user to enter the size of an array and allow
the user to input the elements
[Link]("Enter the size of the array: ");
int size = [Link]();
int[] arr = new int[size];
[Link]("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = [Link]();
}

// Display the entered array


[Link]("Entered array: ");
for (int i = 0; i < size; i++) {
[Link](arr[i] + " ");
}
[Link]();

// 1) Find and Display: Sum of all elements in the array


int sum = 0;
for (int i : arr) {
sum += i;
}
[Link]("Sum of all elements: " + sum);

// 2) Find and Display: Average of the elements


double average = (double) sum / size;
[Link]("Average of the elements: " + average);

// 3) Find and Display: Maximum and minimum values in the


array
int max = arr[0];
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
[Link]("Maximum value in the array: " + max);
[Link]("Minimum value in the array: " + min);

// 4) Search: Prompt the user to enter a value to search for in the


array
[Link]("Enter a value to search for in the array: ");
int searchValue = [Link]();
boolean found = false;
int index = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == searchValue) {
found = true;
index = i;
break;
}
}
if (found) {
[Link](searchValue + " is present in the array at
index " + index);
} else {
[Link](searchValue + " is not present in the
array");
}

[Link]();
}
}

4. BankAccount class is defined with methods for deposit,


withdrawal, and getting the balance. The withdraw method throws a
custom InsufficientFundsException if the withdrawal amount exceeds
the account balance.
The BankApplication class shows the use of this bank account by
taking user inputs for account details, deposit, and withdrawal
amounts. It includes a try-catch block to handle the custom exception
and a finally block to display the current balance regardless of
whether an exception occurred or not.
package adsf;
import [Link];

class InsufficientFundsException extends Exception {


public InsufficientFundsException(String message) {
super(message);
}
}

class BankAccount {
private String accountHolderName;
private double balance;

public BankAccount(String accountHolderName, double


initialBalance) {
[Link] = accountHolderName;
[Link] = initialBalance;
}
public void deposit(double amount) {
balance += amount;
[Link]("Deposit successful. Current balance: " +
balance);
}

public void withdraw(double amount) throws


InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds.
Cannot withdraw " + amount);
}
balance -= amount;
[Link]("Withdrawal successful. Current balance: " +
balance);
}

public double getBalance() {


return balance;
}
}

public class BankApplication {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// User inputs for account details
[Link]("Enter account holder name: ");
String accountHolderName = [Link]();
[Link]("Enter initial balance: ");
double initialBalance = [Link]();

// Creating BankAccount object


BankAccount bankAccount = new
BankAccount(accountHolderName, initialBalance);

try {
// User input for deposit amount
[Link]("Enter deposit amount: ");
double depositAmount = [Link]();
[Link](depositAmount);

// User input for withdrawal amount


[Link]("Enter withdrawal amount: ");
double withdrawalAmount = [Link]();
[Link](withdrawalAmount);
} catch (InsufficientFundsException e) {
[Link]("Exception: " + [Link]());
} finally {
// Displaying the current balance
[Link]("Current balance: " +
[Link]());
[Link]();
}
}
}

5.
Create a arraylist for software companies [Google, Apple, Microsoft,
Amazon, Facebook] and Perform following operations on Arraylist :

1. Add a new software company name in the above arraylist-


CapGemini, and display the output.
2. Replace the 3rd company from an array list with a new company
name and display the output.
3. Delete the 4th company from the array list and display the
arraylist
4. Add sub arraylist in the above arraylist-
[Walmart,Cognizant,HSBC] and display the output.
5. Search that given company name is exist in arrayList or not.

package adsf;
import [Link];
import [Link];

public class SoftwareCompaniesArrayList {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Create an ArrayList of software companies
ArrayList<String> softwareCompanies = new ArrayList<>();
[Link]("Google");
[Link]("Apple");
[Link]("Microsoft");
[Link]("Amazon");
[Link]("Facebook");

// Display the original list


[Link]("Original List: " + softwareCompanies);

// 1. Add a new software company - CapGemini


[Link]("Enter a new software company to add: ");
String newCompany = [Link]();
[Link](newCompany);
[Link]("1. Added " + newCompany + ": " +
softwareCompanies);

// 2. Replace the 3rd company with a new company name


[Link]("Enter a new name for the 3rd company: ");
String newName = [Link]();
[Link](2, newName);
[Link]("2. Replaced 3rd company with " + newName
+ ": " + softwareCompanies);
// 3. Delete the 4th company
String deletedCompany = [Link](3);
[Link]("3. Deleted 4th company: " +
deletedCompany);

// Display the updated list


[Link]("Updated List: " + softwareCompanies);

// 4. Add a sub ArrayList


ArrayList<String> subCompanies = new ArrayList<>();
[Link]("Walmart");
[Link]("Cognizant");
[Link]("HSBC");

[Link]([Link](subCompanies));
[Link]("4. Added sub ArrayList: " +
softwareCompanies);

// 5. Search for a given company name


[Link]("Enter a company name to search: ");
String searchCompany = [Link]();
boolean isCompanyExists =
[Link](searchCompany);
[Link]("5. Is " + searchCompany + " in the list? " +
isCompanyExists);

[Link]();
}
}

6. You are tasked with creating a Java program that counts the number
of unique words in a given text using a HashSet.
Requirements:
WordCounter Class:

 Create a WordCounter class that includes the following:


 A method countUniqueWords(String text) that takes a text as
input and returns the count of unique words.
 Use a HashSet to store unique words.
 Consider a word as any sequence of characters separated by
whitespace.
Main Application:

 Implement a main application that demonstrates the


functionality of the WordCounter class.
 Allow the user to input a text string.
 Use the WordCounter class to count and display the number of
unique words in the input text.
Sample Output :
Enter a text string: This is a simple Java program. Java is powerful
and simple.
Number of unique words: 8
package adsf;
import [Link].*;

class WordCounter {
public int countUniqueWords(String text) {
Set<String> uniqueWords = new HashSet<>();
String[] words = [Link]("\\s+");

for (String word : words) {


[Link]([Link]()); // Convert to
lowercase to consider words as case-insensitive
}

return [Link]();
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
WordCounter wordCounter = new WordCounter();

[Link]("Enter a text string: ");


String inputText = [Link]();
int uniqueWordCount =
[Link](inputText);
[Link]("Number of unique words: " +
uniqueWordCount);

[Link]();
}
}

7. Write a Java program to create a class called Student with private


instance variables student_id, student_name, and grades. Provide
public getter and setter methods to access and modify the student_id
and student_name variables. However, provide a method called
addGrade() that allows adding a grade to the grades variable while
performing additional validation.
Sample I/P Please Enter Your Id:1001,
Please Enter Your Name:Rahul Jadhav,
Please Enter Your Marks: 90 78 87 91 (Use ArrayList to store the
marks)
Sample output: Student ID: 1001
Student Name: Rahul Jadhav
Grades: [90, 78, 87, 91]

package adsf;
import [Link];
import [Link];

class Student {
private int student_id;
private String student_name;
ArrayList<Integer> grades;

public int getStudentId() {


return student_id;
}

public void setStudentId(int student_id) {


this.student_id = student_id;
}

public String getStudentName() {


return student_name;
}

public void setStudentName(String student_name) {


this.student_name = student_name;
}

public ArrayList<Integer> getGrades() {


return grades;
}

public void addGrade(int grade) {


// Additional validation can be added here
if (grade >= 0 && grade <= 100) {
[Link](grade);
} else {
[Link]("Invalid grade. Please enter a grade
between 0 and 100.");
}
}
}

public class StudentTest {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Create a Student object


Student student = new Student();

// Input student details


[Link]("Please Enter Your Id: ");
int studentId = [Link]();
[Link](studentId);
[Link](); // Consume the newline character

[Link]("Please Enter Your Name: ");


String studentName = [Link]();
[Link](studentName);

[Link]("Please Enter Your Marks (separated by


spaces): ");
String marksInput = [Link]();
String[] marksArray = [Link](" ");
ArrayList<Integer> grades = new ArrayList<>();

for (String mark : marksArray) {


[Link]([Link](mark));
}

[Link] = grades; // Assign grades directly (without using


the setter) for simplicity

// Display student details


[Link]("\nStudent ID: " + [Link]());
[Link]("Student Name: " +
[Link]());
[Link]("Grades: " + [Link]());
[Link]();
}
}

8. Write a Java program to create a banking system with three


classes - Bank, Account, SavingsAccount, and CurrentAccount. The
bank should have a list of accounts and methods for adding them.
Accounts should be an interface with methods to deposit, withdraw,
calculate interest, and view balances. SavingsAccount and
CurrentAccount should implement the Account interface and have
their own unique methods.

Case1:Savings Account:
Initial Deposit: 1000.00
Interest rate: 1.25%
Case 2:Current Account:
Initial Deposit: 5000.00
OverdraftLimit: 1000.00
Case3:Deposit to Account:
Now 100 to Savings Account.
Now deposit 500 to Current Account
Case4:Withdraw from Account:
Withdraw 150 from Savings Account.
Case5: Account Balance:
Savings A/c and Current A/c.:
Account balance: 950.0
Account balance: 5500.0
Case6: Apply Intrest:
After applying interest on Savings A/c for 1 year:
Savings A/c and Current A/c.:
Account balance: 961.875
Account balance: 5500.0
package adsf;
import [Link];

interface Account {
void deposit(double amount);

void withdraw(double amount);

void calculateInterest();

double getBalance();
}

class SavingsAccount implements Account {


private double balance;
private double interestRate;

public SavingsAccount(double initialDeposit, double interestRate)


{
[Link] = initialDeposit;
[Link] = interestRate;
}

@Override
public void deposit(double amount) {
balance += amount;
}

@Override
public void withdraw(double amount) {
balance -= amount;
}

@Override
public void calculateInterest() {
balance += balance * (interestRate / 100);
}

@Override
public double getBalance() {
return balance;
}
}

class CurrentAccount implements Account {


private double balance;
private double overdraftLimit;

public CurrentAccount(double initialDeposit, double


overdraftLimit) {
[Link] = initialDeposit;
[Link] = overdraftLimit;
}

@Override
public void deposit(double amount) {
balance += amount;
}

@Override
public void withdraw(double amount) {
if (balance - amount >= -overdraftLimit) {
balance -= amount;
} else {
[Link]("Withdrawal exceeds overdraft limit.
Transaction cancelled.");
}
}

@Override
public void calculateInterest() {
// Current account does not earn interest
}

@Override
public double getBalance() {
return balance;
}
}

class Bank {
private Account[] accounts;

public Bank(Account[] accounts) {


[Link] = accounts;
}

public void displayBalances() {


for (Account account : accounts) {
[Link]("Account balance: " +
[Link]());
}
}

public void applyInterest() {


for (Account account : accounts) {
[Link]();
}
}
}
public class BankingSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Create SavingsAccount
[Link]("Case 1: Savings Account");
[Link]("Initial Deposit: ");
double initialDepositSavings = [Link]();
[Link]("Interest Rate: ");
double interestRateSavings = [Link]();
Account savingsAccount = new
SavingsAccount(initialDepositSavings, interestRateSavings);

// Create CurrentAccount
[Link]("Case 2: Current Account");
[Link]("Initial Deposit: ");
double initialDepositCurrent = [Link]();
[Link]("Overdraft Limit: ");
double overdraftLimit = [Link]();
Account currentAccount = new
CurrentAccount(initialDepositCurrent, overdraftLimit);

// Create Bank with accounts


Bank bank = new Bank(new Account[]{savingsAccount,
currentAccount});

// Deposit to accounts
[Link]("Case 3: Deposit to Account");
[Link]("Deposit to Savings Account: ");
double depositToSavings = [Link]();
[Link](depositToSavings);

[Link]("Deposit to Current Account: ");


double depositToCurrent = [Link]();
[Link](depositToCurrent);

// Withdraw from accounts


[Link]("Case 4: Withdraw from Account");
[Link]("Withdraw from Savings Account: ");
double withdrawFromSavings = [Link]();
[Link](withdrawFromSavings);

// Display balances
[Link]("Case 5: Account Balance");
[Link]("Savings A/c balance: " +
[Link]());
[Link]("Current A/c balance: " +
[Link]());
// Apply interest
[Link]("Case 6: Apply Interest");
[Link]("After applying interest on Savings A/c for 1
year:");
[Link]();
[Link]("Savings A/c and Current A/c.:");
[Link]("Savings A/c balance: " +
[Link]());
[Link]("Current A/c balance: " +
[Link]());

[Link]();
}
}

9. You are tasked with developing a simple Vehicle Rental System


in Java. The system should allow users to rent different types of
vehicles, such as cars and bicycles. Implement an class called Vehicle
to represent the common attributes and behaviors of all vehicles.
Then, create two subclasses, Car and Bicycle, that inherit from the
Vehicle class.
Requirement:
Vehicle Class: Include the following attributes:

 id (unique identifier for each vehicle)


 brand (the brand or make of the vehicle)
 rentalRate (the cost per hour for renting the vehicle)
Include the following methods:
 displayDetails() (display the details of the vehicle)
 calculateRentalCost(int hours) (calculate the total rental cost
based on the rental rate and the number of hours)

Car Class:

 Extend the Vehicle class. Include an additional attribute:


numSeats (the number of seats in the car) Override the
displayDetails() method to include car-specific details.
 Bicycle Class:
 Extend the Vehicle class. Include an additional attribute:
type (the type of bicycle, e.g., mountain bike, road bike)
 Override the displayDetails() method to include bicycle-
specific details.
 Main Application:
 Implement a main application that demonstrates the
functionality of the system.
 Allow users to:
o Add new cars and bicycles to the system with their
details.
o Display the details of all available vehicles.
o Rent a vehicle by specifying the vehicle ID and the
number of hours.
o Display the rental details, including the total cost.
o

package adsf;
import [Link];
import [Link];

class Vehicle {
private static int nextId = 1;

protected int id;


protected String brand;
protected double rentalRate;
public Vehicle(String brand, double rentalRate) {
[Link] = nextId++;
[Link] = brand;
[Link] = rentalRate;
}

public void displayDetails() {


[Link]("ID: " + id);
[Link]("Brand: " + brand);
[Link]("Rental Rate: $" + rentalRate + " per hour");
}

public double calculateRentalCost(int hours) {


return rentalRate * hours;
}
}

class Car extends Vehicle {


private int numSeats;

public Car(String brand, double rentalRate, int numSeats) {


super(brand, rentalRate);
[Link] = numSeats;
}
@Override
public void displayDetails() {
[Link]();
[Link]("Number of Seats: " + numSeats);
}
}

class Bicycle extends Vehicle {


private String type;

public Bicycle(String brand, double rentalRate, String type) {


super(brand, rentalRate);
[Link] = type;
}

@Override
public void displayDetails() {
[Link]();
[Link]("Type: " + type);
}
}

public class VehicleRentalSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
ArrayList<Vehicle> vehicles = new ArrayList<>();

while (true) {
[Link]("\nVehicle Rental System");
[Link]("1. Add a Car");
[Link]("2. Add a Bicycle");
[Link]("3. Display details of all vehicles");
[Link]("4. Rent a vehicle");
[Link]("5. Exit");
[Link]("Choose an option: ");
int choice = [Link]();

switch (choice) {
case 1:
addCar(scanner, vehicles);
break;
case 2:
addBicycle(scanner, vehicles);
break;
case 3:
displayAllVehicles(vehicles);
break;
case 4:
rentVehicle(scanner, vehicles);
break;
case 5:
[Link]("Exiting the Vehicle Rental System.
Goodbye!");
[Link]();
[Link](0);
break;
default:
[Link]("Invalid option. Please try again.");
}
}
}

private static void addCar(Scanner scanner, ArrayList<Vehicle>


vehicles) {
[Link]("\nAdd a Car");
[Link]("Enter the brand: ");
String brand = [Link]();

[Link]("Enter the rental rate per hour: ");


double rentalRate = [Link]();

[Link]("Enter the number of seats: ");


int numSeats = [Link]();
[Link](new Car(brand, rentalRate, numSeats));
[Link]("Car added successfully!");
}

private static void addBicycle(Scanner scanner,


ArrayList<Vehicle> vehicles) {
[Link]("\nAdd a Bicycle");
[Link]("Enter the brand: ");
String brand = [Link]();

[Link]("Enter the rental rate per hour: ");


double rentalRate = [Link]();

[Link]("Enter the type of bicycle: ");


String type = [Link]();

[Link](new Bicycle(brand, rentalRate, type));


[Link]("Bicycle added successfully!");
}

private static void displayAllVehicles(ArrayList<Vehicle>


vehicles) {
[Link]("\nDetails of All Vehicles");
for (Vehicle vehicle : vehicles) {
[Link]();
[Link]("---------------------------");
}
}

private static void rentVehicle(Scanner scanner,


ArrayList<Vehicle> vehicles) {
[Link]("\nRent a Vehicle");
displayAllVehicles(vehicles);

[Link]("Enter the ID of the vehicle you want to rent:


");
int vehicleId = [Link]();

[Link]("Enter the number of hours to rent: ");


int hours = [Link]();

Vehicle selectedVehicle = findVehicleById(vehicles, vehicleId);

if (selectedVehicle != null) {
double totalCost =
[Link](hours);
[Link]("\nRental Details");
[Link]();
[Link]("Rental Duration: " + hours + " hours");
[Link]("Total Cost: $" + totalCost);
} else {
[Link]("Vehicle not found with ID: " + vehicleId);
}
}

private static Vehicle findVehicleById(ArrayList<Vehicle>


vehicles, int id) {
for (Vehicle vehicle : vehicles) {
if ([Link] == id) {
return vehicle;
}
}
return null;
}
}

10.

a. Check that given number is Armstrong or [Link]-


153=13+53+33=1+225+27=153
b. Write a Java program to check whether two strings are
anagram or not? RACE and CARE are anagram strings.

c. Take two DOB in string format from user .Compare it and


display the messages as “Younger”, ”Elder” or “Same age”.
package adsf;
import [Link];
import [Link];
import [Link];
import [Link];

public class StringNumberComparison {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Task a: Check if a number is Armstrong or not


[Link]("Enter a number to check if it's Armstrong: ");
int number = [Link]();
if (isArmstrong(number)) {
[Link](number + " is an Armstrong number.");
} else {
[Link](number + " is not an Armstrong number.");
}

// Task b: Check if two strings are anagrams


[Link]("Enter the first string: ");
String str1 = [Link]().toLowerCase();

[Link]("Enter the second string: ");


String str2 = [Link]().toLowerCase();

if (areAnagrams(str1, str2)) {
[Link](str1 + " and " + str2 + " are anagrams.");
} else {
[Link](str1 + " and " + str2 + " are not
anagrams.");
}

// Task c: Compare two dates of birth and display age


comparison
[Link]("Enter the first date of birth (YYYY-MM-DD):
");
String dob1 = [Link]();

[Link]("Enter the second date of birth (YYYY-MM-


DD): ");
String dob2 = [Link]();

compareDOB(dob1, dob2);

[Link]();
}

// Task a: Check if a number is Armstrong or not


private static boolean isArmstrong(int number) {
int originalNumber, remainder, result = 0, n = 0;

originalNumber = number;
while (originalNumber != 0) {
originalNumber /= 10;
++n;
}

originalNumber = number;
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += [Link](remainder, n);
originalNumber /= 10;
}

return result == number;


}

// Task b: Check if two strings are anagrams


private static boolean areAnagrams(String str1, String str2) {
char[] charArray1 = [Link]();
char[] charArray2 = [Link]();

[Link](charArray1);
[Link](charArray2);

return [Link](charArray1, charArray2);


}

// Task c: Compare two dates of birth and display age comparison


private static void compareDOB(String dob1, String dob2) {
DateTimeFormatter formatter =
[Link]("yyyy-MM-dd");
LocalDate date1 = [Link](dob1, formatter);
LocalDate date2 = [Link](dob2, formatter);

if ([Link](date2)) {
[Link]("Person with the first date of birth is
elder.");
} else if ([Link](date2)) {
[Link]("Person with the first date of birth is
younger.");
} else {
[Link]("Both persons have the same age.");
}
}
}
11. a. Write a program to create and traverse (or iterate) ArrayList
using for-loop,

iterator, and advance for-loop.

b. check if element(value) exists in ArrayList?

c. add element at particular index of ArrayList?

d. remove element at particular index of ArrayList?

e. sort a given array list.([Link]())

f. reverse elements in an array list.

g. compare two array lists.

h. find first and last occurrence of repeated element.

package adsf;
import [Link];
import [Link];
import [Link];
import [Link];

public class ArrayListOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
ArrayList<Integer> arrayList = new ArrayList<>();
// a. Create and traverse ArrayList using for-loop, iterator, and
advance for-loop
[Link]("Enter elements for the ArrayList (enter -1 to
stop):");
int element;
while ((element = [Link]()) != -1) {
[Link](element);
}

[Link]("Traverse ArrayList using for-loop:");


for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
[Link]();

[Link]("Traverse ArrayList using iterator:");


Iterator<Integer> iterator = [Link]();
while ([Link]()) {
[Link]([Link]() + " ");
}
[Link]();

[Link]("Traverse ArrayList using advance for-


loop:");
for (int num : arrayList) {
[Link](num + " ");
}
[Link]();

// b. Check if element exists in ArrayList


[Link]("Enter an element to check if it exists in the
ArrayList: ");
int checkElement = [Link]();
if ([Link](checkElement)) {
[Link](checkElement + " exists in the
ArrayList.");
} else {
[Link](checkElement + " does not exist in the
ArrayList.");
}

// c. Add element at a particular index of ArrayList


[Link]("Enter the element to add: ");
int addElement = [Link]();
[Link]("Enter the index where you want to add the
element: ");
int addIndex = [Link]();
[Link](addIndex, addElement);
[Link]("Element added at index " + addIndex + ": "
+ arrayList);
// d. Remove element at a particular index of ArrayList
[Link]("Enter the index from which you want to
remove the element: ");
int removeIndex = [Link]();
[Link](removeIndex);
[Link]("Element removed from index " +
removeIndex + ": " + arrayList);

// e. Sort the ArrayList


[Link](arrayList);
[Link]("ArrayList after sorting: " + arrayList);

// f. Reverse elements in the ArrayList


[Link](arrayList);
[Link]("ArrayList after reversing: " + arrayList);

// g. Compare two ArrayLists


ArrayList<Integer> secondArrayList = new ArrayList<>();
[Link]("Enter elements for the second ArrayList
(enter -1 to stop):");
while ((element = [Link]()) != -1) {
[Link](element);
}
if ([Link](secondArrayList)) {
[Link]("The two ArrayLists are equal.");
} else {
[Link]("The two ArrayLists are not equal.");
}

// h. Find first and last occurrence of repeated element


[Link]("Enter an element to find its first and last
occurrence: ");
int findElement = [Link]();
int firstOccurrence = [Link](findElement);
int lastOccurrence = [Link](findElement);

if (firstOccurrence != -1) {
[Link]("First occurrence of " + findElement + " is
at index " + firstOccurrence);
[Link]("Last occurrence of " + findElement + " is
at index " + lastOccurrence);
} else {
[Link](findElement + " not found in the
ArrayList.");
}

[Link]();
}
}

12. a. Create arrayList, add the integer elements in arrayList using


asList().Remove the duplicate values and return a arrayList containing
unique values. Implement the logic inside removeDuplicates()
method. Test the functionalities using the main () method of the Tester
class. Sample Input and Output---------10, 20, 10, 15,40,15,40 ---
10,20,15,40

b. Given two lists, concatenate the second list in reverse order to the
end of the first list and return the concatenated list. Implement the
logic inside concatenateLists() method. listOne = Hello 102 200.8 25
listTwo = 150 40.8 welcome A output: Hello 102 200.8 25 A welcome
40.8 150

a.

package adsf;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class aa {
public static void main(String[] args) {
// Taking input from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter integers separated by commas: ");
String input = [Link]();

// Converting input string to ArrayList


List<Integer> inputList = parseInput(input);

// Removing duplicates
List<Integer> uniqueList = removeDuplicates(inputList);

// Printing unique values


[Link]("Unique values: " + uniqueList);
}

private static List<Integer> parseInput(String input) {


// Splitting the input string and converting to Integer list
String[] elements = [Link](",");
List<Integer> inputList = new ArrayList<>();
for (String element : elements) {
[Link]([Link]([Link]()));
}
return inputList;
}

private static List<Integer> removeDuplicates(List<Integer>


inputList) {
// Using HashSet to remove duplicates
Set<Integer> uniqueSet = new HashSet<>(inputList);
return new ArrayList<>(uniqueSet);
}
}

b.

package adsf;
import [Link];
import [Link];
import [Link];

public class Tester{


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
ArrayList<String> listOne = getListFromUser(scanner);
ArrayList<String> listTwo = getListFromUser(scanner);

ArrayList<String> result = concatenateLists(listOne, listTwo);


[Link]("Concatenated list: " + result);
}

public static ArrayList<String> getListFromUser(Scanner scanner)


{
ArrayList<String> list = new ArrayList<>();
[Link]("Enter the number of elements: ");
int n = [Link]();
[Link]("Enter the elements: ");
for (int i = 0; i < n; i++) {
[Link]([Link]());
}
return list;
}

public static ArrayList<String>


concatenateLists(ArrayList<String> listOne, ArrayList<String>
listTwo) {
ArrayList<String> result = new ArrayList<>(listOne);
[Link](listTwo);
[Link](listTwo);
return result;
}
}
13.a) Implement the method findNumbers accepting two numbers
num1 and num2 based on the conditions given below:
Validate that num1 should be less than num2 .If the validations are
successful
populate all the 2 digit positive numbers between num1 and num2
into the provided numbers array if sum of the digits of the number is a
multiple of 3
number is a multiple of 5 Return the numbers array
Test the functionalities using the main method of the Tester class.

b) Program to add any two given matrices and print the result.

a.

package adsf;
import [Link];
import [Link];
import [Link];

public class ed {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input num1 and num2 from the user


[Link]("Enter num1: ");
int num1 = [Link]();
[Link]("Enter num2 (should be greater than num1):
");
int num2 = [Link]();

// Call the findNumbers method and test the functionality


List<Integer> result = findNumbers(num1, num2);

// Print the result


[Link]("Resulting Numbers: " + result);
}

private static List<Integer> findNumbers(int num1, int num2) {


// Validate that num1 should be less than num2
if (num1 >= num2) {
[Link]("Invalid input: num1 should be less than
num2");
return new ArrayList<>(); // Returning an empty list
indicating failure
}

List<Integer> numbers = new ArrayList<>();


for (int i = num1; i <= num2; i++) {
if (i >= 10 && i <= 99) {
int sumOfDigits = (i % 10) + (i / 10);
if (sumOfDigits % 3 == 0 && i % 5 == 0) {
[Link](i);
}
}
}

return numbers;
}
}

b.

package adsf;
import [Link];

public class MatrixAddition {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input the number of rows and columns for the matrices


[Link]("Enter the number of rows for the matrices:
");
int rows = [Link]();

[Link]("Enter the number of columns for the


matrices: ");
int cols = [Link]();

// Input matrices from the user


int[][] matrix1 = inputMatrix("Enter elements for Matrix 1:",
rows, cols);
int[][] matrix2 = inputMatrix("Enter elements for Matrix 2:",
rows, cols);

// Add matrices and print the result


int[][] result = addMatrices(matrix1, matrix2);
[Link]("Resultant Matrix after addition:");
printMatrix(result);
}

private static int[][] inputMatrix(String prompt, int rows, int cols) {


Scanner scanner = new Scanner([Link]);

[Link](prompt);
int[][] matrix = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
[Link]("Enter element at position (%d, %d): ", i
+ 1, j + 1);
matrix[i][j] = [Link]();
}
}

return matrix;
}

private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {


int rows = [Link];
int cols = matrix1[0].length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return result;
}

private static void printMatrix(int[][] matrix) {


int rows = [Link];
int cols = matrix[0].length;

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}

14) A Company manufactures Vehicles, which could be a Helicopter,


a Car, or a Train depending on the customer’s demand. Each Vehicle
instance has a method called move, which prints on the console the
nature of movement of the vehicle. For example, the Helicopter Flies
in Air, the Car Drives on Road and the Train Runs on Track. Write a
program that accepts input from the user on the kind of vehicle the
user wants to order, and the system should print out nature of
movement. Implement all Java coding best practices to implement
this program.

package adsf;

import [Link];

// Abstract class representing the common behavior of all vehicles


abstract class Vehicle {
// Method to move the vehicle
abstract void move();
}

// Concrete class representing a Helicopter


class Helicopter extends Vehicle {
@Override
void move() {
[Link]("Helicopter flies in the air.");
}
}

// Concrete class representing a Car


class Car extends Vehicle {
@Override
void move() {
[Link]("Car drives on the road.");
}
}

// Concrete class representing a Train


class Train extends Vehicle {
@Override
void move() {
[Link]("Train runs on the track.");
}
}

public class maina {


public static void main(String[] args) {
// Create Scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Prompt user to enter the type of vehicle


[Link]("Enter the type of vehicle you want to order
(Helicopter/Car/Train): ");
String vehicleType = [Link]();

// Create a vehicle based on user input


Vehicle vehicle = createVehicle(vehicleType);

// If the entered vehicle type is valid, move the vehicle


if (vehicle != null) {
// Move the vehicle
[Link]();
} else {
// Invalid input
[Link]("Invalid vehicle type. Please choose
Helicopter, Car, or Train.");
}
// Close the scanner to avoid resource leaks
[Link]();
}

// Factory method to create a vehicle based on user input


private static Vehicle createVehicle(String vehicleType) {
switch ([Link]()) {
case "helicopter":
return new Helicopter();
case "car":
return new Car();
case "train":
return new Train();
default:
return null; // Invalid vehicle type
}
}
}

15) You are required to compute the power of a number by


implementing a calculator. Create a class My Calculator which
consists of a single method long power (int, int). This method takes
two integers n and p, as parameters and finds (n)p. If either or is
negative, then the method must throw an exception which says " n or
p should not be negative”. Also, if both and are zero, then the method
must throw an exception which says "n or p should not be negative”.

package adsf;
import [Link];

class MyCalculator {
long power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
throw new Exception("n or p should not be negative");
} else if (n == 0 && p == 0) {
throw new Exception("n and p should not be zero");
} else {
return (long) [Link](n, p);
}
}
}

public class calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the base (n): ");


int base = [Link]();
[Link]("Enter the exponent (p): ");
int exponent = [Link]();

try {
MyCalculator calculator = new MyCalculator();
long result = [Link](base, exponent);
[Link]("Result: " + result);
} catch (Exception e) {
[Link]("Error: " + [Link]());
} finally {
[Link]();
}
}
}

16) . Write a Java Program to iterate ArrayList using for-loop, iterator,


and advance for-loop. Insert 3 Array [Link] 20 30 40Output:

iterator Loop:
20
30
40
Advanced For Loop:
20
30
40
For Loop:
20
30
40

package adsf;

import [Link];
import [Link];
import [Link];

public class loop {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Create three ArrayLists


ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
ArrayList<Integer> list3 = new ArrayList<>();

// Populate ArrayLists with user input


[Link]("Enter elements for ArrayList 1 (separated by
spaces): ");
populateList(list1, scanner);

[Link]("Enter elements for ArrayList 2 (separated by


spaces): ");
populateList(list2, scanner);

[Link]("Enter elements for ArrayList 3 (separated by


spaces): ");
populateList(list3, scanner);

// Iterate using iterator


[Link]("\nIterator Loop:");
iterateWithIterator(list1);
iterateWithIterator(list2);
iterateWithIterator(list3);

// Iterate using advanced for-loop


[Link]("\nAdvanced For Loop:");
iterateWithAdvancedForLoop(list1);
iterateWithAdvancedForLoop(list2);
iterateWithAdvancedForLoop(list3);

// Iterate using for-loop


[Link]("\nFor Loop:");
iterateWithForLoop(list1);
iterateWithForLoop(list2);
iterateWithForLoop(list3);
// Close the scanner
[Link]();
}

private static void populateList(ArrayList<Integer> list, Scanner


scanner) {
String[] elements = [Link]().split(" ");
for (String element : elements) {
[Link]([Link](element));
}
}

private static void iterateWithIterator(ArrayList<Integer> list) {


Iterator<Integer> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}

private static void


iterateWithAdvancedForLoop(ArrayList<Integer> list) {
for (int element : list) {
[Link](element);
}
}
private static void iterateWithForLoop(ArrayList<Integer> list) {
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
}
}

17) Write a program to implement following inheritance. Accept data


for 5 persons and display the name of employee having salary greater
than 5000.

Class Name: Person


Member variables:
Name, age

Class Name: Employee


Member variables:
Designation, salary

package adsf;
import [Link];

class Person {
String name;
int age;
// Constructor for Person
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Display method for Person


public void displayPersonInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

class Employee extends Person {


String designation;
double salary;

// Constructor for Employee


public Employee(String name, int age, String designation, double
salary) {
super(name, age);
[Link] = designation;
[Link] = salary;
}
// Display method for Employee
public void displayEmployeeInfo() {
// Call the display method of the superclass (Person)
displayPersonInfo();

[Link]("Designation: " + designation);


[Link]("Salary: " + salary);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Create an array to store information for 5 persons


Employee[] employees = new Employee[5];

// Accept data for 5 persons


for (int i = 0; i < 5; i++) {
[Link]("Enter details for Person " + (i + 1) + ":");
[Link]("Name: ");
String name = [Link]();
[Link]("Age: ");
int age = [Link]();
[Link](); // Consume the newline character
[Link]("Designation: ");
String designation = [Link]();
[Link]("Salary: ");
double salary = [Link]();
[Link](); // Consume the newline character

// Create an Employee object and store it in the array


employees[i] = new Employee(name, age, designation,
salary);
}

// Display the information for all persons


[Link]("\nDetails for all persons:");
for (Employee employee : employees) {
[Link]();
[Link]();
}

// Display the name of employees with salary greater than 5000


[Link]("\nEmployees with salary greater than
5000:");
for (Employee employee : employees) {
if ([Link] > 5000) {
[Link]([Link]);
}
}

// Close the scanner


[Link]();
}
}

18) Create a class Student with attributes roll no, name, age and
course. Initialize values through parameterized constructor. If age of
student is not in between 15 and 21 then generate user-defined
exception "AgeNotWithinRangeException". If name contains
numbers or special symbols raise exception
"NameNotValidException". Define the two exception classes.

package adsf;
import [Link];

// Custom exception for age validation


class AgeNotWithinRangeException extends Exception {
AgeNotWithinRangeException(String message) {
super(message);
}
}
// Custom exception for name validation
class NameNotValidException extends Exception {
NameNotValidException(String message) {
super(message);
}
}

// Student class
class emp {
private int rollNo;
private String name;
private int age;
private String course;

// Parameterized constructor
emp(int rollNo, String name, int age, String course) throws
AgeNotWithinRangeException, NameNotValidException {
if (age < 15 || age > 21) {
throw new AgeNotWithinRangeException("Age should be
between 15 and 21.");
}

if (![Link]("^[a-zA-Z ]+$")) {
throw new NameNotValidException("Name should only
contain letters and spaces.");
}

[Link] = rollNo;
[Link] = name;
[Link] = age;
[Link] = course;
}

// Display method
void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Course: " + course);
}
}

public class stud {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

try {
// Input from the user
[Link]("Enter Roll No: ");
int rollNo = [Link]();
[Link]("Enter Name: ");
[Link](); // Consume the newline character left by
nextInt()
String name = [Link]();

[Link]("Enter Age: ");


int age = [Link]();

[Link]("Enter Course: ");


[Link](); // Consume the newline character left by
nextInt()
String course = [Link]();

// Create a Student object


emp student = new emp(rollNo, name, age, course);

// Display student details


[Link]("\nStudent Details:");
[Link]();
} catch (AgeNotWithinRangeException |
NameNotValidException e) {
[Link]("Error: " + [Link]());
} catch (Exception e) {
[Link]("An unexpected error occurred.");
} finally {
[Link]();
}
}
}

19) Write a Java Program to count the number of words in a string


using HashMap. Output:
Input :Enter String: "This this is is done by Saket Saket";
{Saket=2, by=1, this=1, This=1, is=2, done=1}

package adsf;
import [Link];
import [Link];
import [Link];

public class WordCount {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter String: ");
String input = [Link]();

Map<String, Integer> wordCountMap = countWords(input);


[Link](wordCountMap);
}

public static Map<String, Integer> countWords(String input) {


String[] words = [Link](" ");
Map<String, Integer> wordCountMap = new HashMap<>();

for (String word : words) {


if ([Link](word)) {
[Link](word, [Link](word) + 1);
} else {
[Link](word, 1);
}
}

return wordCountMap;
}
}

20)

a) Write a Java program to display the pattern like a diamond.


Input number of rows (half of the diamond) :7 Expected
Output :
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
B ) Display the letter L in star pattern.

*
*
*
* * * *

a)
package adsf;
import [Link];

public class DiamondPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input from the user
[Link]("Enter the number of rows (half of the
diamond): ");
int rows = [Link]();

// Display upper half of the diamond


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}

// Display lower half of the diamond


for (int i = rows - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}

[Link]();
}
}
b) package adsf;

import [Link];

public class LetterLStarPattern {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Input from the user

[Link]("Enter the size of the letter L: ");

int size = [Link]();

// Display letter L in star pattern

for (int i = 0; i < size; i++) {

[Link]("*");

for (int i = 0; i < size / 2; i++) {

[Link]("* *");

}
[Link]();

21) We have to calculate the percentage of marks obtained in three


subjects (each out of 100) by student A and in four subjects (each out
of 100) by student B. Create an abstract class 'Marks' with an abstract
method 'getPercentage'. It is inherited by two other classes 'A' and 'B'
each having a method with the same name which returns the
percentage of the students. The constructor of student A takes the
marks in three subjects as its parameters and the marks in four
subjects as its parameters for student

B. Create an object for eac of the two classes and print the percentage
of marks for both the students.
package adsf;

import [Link];

// Abstract class Marks


abstract class Marks {
abstract double getPercentage();
}

// Class A inheriting from Marks


class A extends Marks {
private double subject1, subject2, subject3;

// Constructor for class A


A(double s1, double s2, double s3) {
this.subject1 = s1;
this.subject2 = s2;
this.subject3 = s3;
}

// Implementation of abstract method to get percentage for class A


@Override
double getPercentage() {
return (subject1 + subject2 + subject3) / 3.0;
}
}

// Class B inheriting from Marks


class B extends Marks {
private double subject1, subject2, subject3, subject4;

// Constructor for class B


B(double s1, double s2, double s3, double s4) {
this.subject1 = s1;
this.subject2 = s2;
this.subject3 = s3;
this.subject4 = s4;
}

// Implementation of abstract method to get percentage for class B


@Override
double getPercentage() {
return (subject1 + subject2 + subject3 + subject4) / 4.0;
}
}

public class subject {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input for student A
[Link]("Enter marks for student A (out of 100):");
[Link]("Subject 1: ");
double s1A = [Link]();
[Link]("Subject 2: ");
double s2A = [Link]();
[Link]("Subject 3: ");
double s3A = [Link]();

// Creating object for class A


A studentA = new A(s1A, s2A, s3A);

// Input for student B


[Link]("Enter marks for student B (out of 100):");
[Link]("Subject 1: ");
double s1B = [Link]();
[Link]("Subject 2: ");
double s2B = [Link]();
[Link]("Subject 3: ");
double s3B = [Link]();
[Link]("Subject 4: ");
double s4B = [Link]();

// Creating object for class B


B studentB = new B(s1B, s2B, s3B, s4B);
// Displaying percentages
[Link]("\nPercentage of student A: " +
[Link]() + "%");
[Link]("Percentage of student B: " +
[Link]() + "%");

[Link]();
}
}

22) 1) Java Program to Count Number of Duplicate Words in String


.2) How to Check if the String Contains 'e' in umbrella
3) Write a Java program to find the common elements between two
arrays of integers.

1)

package adsf;
import [Link];
import [Link];
import [Link];

public class DuplicateWordCount {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input from the user


[Link]("Enter a string: ");
String inputString = [Link]();

// Count duplicate words using HashMap


Map<String, Integer> wordCountMap = new HashMap<>();
String[] words = [Link]("\\s+");

for (String word : words) {


word = [Link]();

if ([Link](word)) {
// If word is already present, increment the count
[Link](word, [Link](word) + 1);
} else {
// If word is not present, add it to the map with count 1
[Link](word, 1);
}
}

// Displaying duplicate words and their counts


[Link]("\nDuplicate words and their counts:");
for ([Link]<String, Integer> entry :
[Link]()) {
if ([Link]() > 1) {
[Link]([Link]() + ": " + [Link]()
+ " times");
}
}

[Link]();
}
}

2)

package adsf;
import [Link];

public class CheckCharacterInString {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input from the user


[Link]("Enter a string: ");
String inputString = [Link]();

// Check if the string contains 'e' in umbrella


boolean containsE = [Link]().contains("e");
// Display the result
if (containsE) {
[Link]("The string contains 'e' in umbrella.");
} else {
[Link]("The string does not contain 'e' in
umbrella.");
}

[Link]();
}
}

3)

package adsf;
import [Link];
import [Link];
import [Link];
import [Link];

public class CommonElementsInArrays {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input for the first array


[Link]("Enter elements for the first array (comma-
separated): ");
String input1 = [Link]();
int[] array1 =
[Link]([Link](",")).mapToInt(Integer::parseInt).toArray(
);

// Input for the second array


[Link]("Enter elements for the second array (comma-
separated): ");
String input2 = [Link]();
int[] array2 =
[Link]([Link](",")).mapToInt(Integer::parseInt).toArray(
);

// Find common elements using Set


Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();

for (int num : array1) {


[Link](num);
}

for (int num : array2) {


[Link](num);
}

[Link](set2);

// Display common elements


[Link]("\nCommon elements between the two
arrays: " + set1);

[Link]();
}
}

23) a) Write a Java program to segregate all 0s on left side and all
1s on right side of a given array of 0s and 1s.

b) Write a Java program to segregate all 0s on left side and all 1s on


right side of a given array of 0s and 1s.

package adsf;
import [Link];

public class SegregateZerosAndOne1 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input from the user
[Link]("Enter the size of the array: ");
int size = [Link]();

int[] array = new int[size];

[Link]("Enter the elements of the array (0s and 1s


only):");
for (int i = 0; i < size; i++) {
array[i] = [Link]();
}

// Segregate 0s and 1s
segregateZerosAndOnes(array, size);

// Display the segregated array


[Link]("\nArray after segregating 0s and 1s:");
for (int value : array) {
[Link](value + " ");
}

[Link]();
}

// Function to segregate 0s and 1s


private static void segregateZerosAndOnes(int[] array, int size) {
int left = 0;
int right = size - 1;

while (left < right) {


// Move left pointer to the right until a 1 is encountered
while (array[left] == 0 && left < right) {
left++;
}

// Move right pointer to the left until a 0 is encountered


while (array[right] == 1 && left < right) {
right--;
}

// Swap 0 at the left pointer with 1 at the right pointer


if (left < right) {
array[left] = 0;
array[right] = 1;
left++;
right--;
}
}
}
}
24) a) Write a Java Program to find the highest number and lowest
number in an array.

a) Calculate and return the sum of all the even numbers


present in the numbers array passed to the method
calculateSumOfEvenNumbers. Implement the logic inside
calculateSumOfE venNumbers() [Link] the
functionalities using the main() method of the Tester class.

package adsf;
import [Link];

public class NumberOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input from the user


[Link]("Enter the size of the array: ");
int size = [Link]();

int[] numbers = new int[size];

[Link]("Enter the elements of the array:");


for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": ");
numbers[i] = [Link]();
}

// Find the highest and lowest numbers


int highestNumber = findHighestNumber(numbers);
int lowestNumber = findLowestNumber(numbers);

// Display the results


[Link]("\nHighest number in the array: " +
highestNumber);
[Link]("Lowest number in the array: " +
lowestNumber);

// Calculate and display the sum of even numbers


int sumOfEvenNumbers =
calculateSumOfEvenNumbers(numbers);
[Link]("Sum of even numbers in the array: " +
sumOfEvenNumbers);

[Link]();
}

// Function to find the highest number in the array


private static int findHighestNumber(int[] array) {
int highest = array[0];
for (int i = 1; i < [Link]; i++) {
if (array[i] > highest) {
highest = array[i];
}
}
return highest;
}

// Function to find the lowest number in the array


private static int findLowestNumber(int[] array) {
int lowest = array[0];
for (int i = 1; i < [Link]; i++) {
if (array[i] < lowest) {
lowest = array[i];
}
}
return lowest;
}

// Function to calculate the sum of even numbers in the array


private static int calculateSumOfEvenNumbers(int[] array) {
int sum = 0;
for (int number : array) {
if (number % 2 == 0) {
sum += number;
}
}
return sum;
}
}

25. 25) a) Write a Java program to create a class known as Person


with methods called getFirstName() and getLastName(). Create a
subclass called Employee that adds a new method named
getEmployeeId() and overrides the getLastName() method to include
the employee's job title.
b) Write a java program to check that given number is prime or not.

a)

package adsf;
import [Link];

// Base class Person


class Person {
private String firstName;
private String lastName;

// Constructor for Person class


public Person(String firstName, String lastName) {
[Link] = firstName;
[Link] = lastName;
}

// Getter method for first name


public String getFirstName() {
return firstName;
}

// Getter method for last name


public String getLastName() {
return lastName;
}
}

// Subclass Employee
class Employee extends Person {
private int employeeId;
private String jobTitle;

// Constructor for Employee class


public Employee(String firstName, String lastName, int
employeeId, String jobTitle) {
super(firstName, lastName);
[Link] = employeeId;
[Link] = jobTitle;
}

// Getter method for employee ID


public int getEmployeeId() {
return employeeId;
}

// Override getLastName() method to include job title


@Override
public String getLastName() {
return [Link]() + ", " + jobTitle;
}
}

public class PersonEmployeeTest {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input for Person


[Link]("Enter first name: ");
String firstName = [Link]();
[Link]("Enter last name: ");
String lastName = [Link]();

// Input for Employee


[Link]("Enter employee ID: ");
int employeeId = [Link]();
[Link](); // Consume the newline character
[Link]("Enter job title: ");
String jobTitle = [Link]();

// Create objects of Person and Employee


Person person = new Person(firstName, lastName);
Employee employee = new Employee(firstName, lastName,
employeeId, jobTitle);

// Display information
[Link]("\nPerson Information:");
[Link]("First Name: " + [Link]());
[Link]("Last Name: " + [Link]());

[Link]("\nEmployee Information:");
[Link]("First Name: " + [Link]());
[Link]("Last Name with Job Title: " +
[Link]());
[Link]("Employee ID: " +
[Link]());

[Link]();
}
}

b)

package adsf;
import [Link];

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input from the user


[Link]("Enter a number: ");
int number = [Link]();

// Check if the number is prime


boolean isPrime = isPrimeNumber(number);

// Display the result


if (isPrime) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}

[Link]();
}

// Function to check if a number is prime


private static boolean isPrimeNumber(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

You might also like