0% found this document useful (0 votes)
12 views43 pages

Name1

sf

Uploaded by

Suraj Mhaske
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)
12 views43 pages

Name1

sf

Uploaded by

Suraj Mhaske
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
You are on page 1/ 43

1. Design a class ‘Complex ‘with data members for real and imaginary part.

Provide default and Parameterized


constructors. Write a program to perform arithmetic operations of two complex numbers.

class Complex { private double real; private double imag;

public Complex() {

this.real = 0; this.imag

= 0; }

// Parameterized constructor public Complex(double

real, double imag) {

this.real = real; this.imag

= imag; }

// Method for adding two complex numbers public Complex add(Complex other)

{ return new Complex(this.real + other.real, this.imag + other.imag); }

// Method for subtracting two complex numbers public Complex

subtract(Complex other) { return new Complex(this.real - other.real, this.imag -

other.imag); }

// Method for multiplying two complex numbers public Complex multiply(Complex

other) { double realPart = (this.real * other.real) - (this.imag * other.imag);

double imagPart = (this.real * other.imag) + (this.imag * other.real); return new

Complex(realPart, imagPart); }

// Method for dividing two complex numbers public Complex

divide(Complex other) { double denominator = other.real *

other.real + other.imag * other.imag; double realPart =

(this.real * other.real + this.imag * other.imag) / denominator;

double imagPart = (this.imag * other.real - this.real * other.imag) /

denominator; return new Complex(realPart, imagPart);

public String toString() { return this.real + " + " + this.imag

""; }

public static void main(String[] args) {

// Creating two complex numbers using parameterized constructor

Complex c1 = new Complex(3, 2);

Complex c2 = new Complex(1, 7);

// Performing arithmetic operations

System.out.println("Complex number 1: " + c1); System.out.println("Complex number 2: "

+ c2);

// Addition

Complex resultAdd = c1.add(c2);


System.out.println("\nAddition: " + resultAdd);

// Subtraction

Complex resultSub = c1.subtract(c2);

System.out.println("Subtraction: " + resultSub);

// Multiplication

Complex resultMul = c1.multiply(c2);

System.out.println("Multiplication: " + resultMul);

// Division

Complex resultDiv = c1.divide(c2);

System.out.println("Division: " + resultDiv);

2. Identify commonalities and differences between Publication, Book and Magazine classes. Title, Price, Copies are common
instance variables and saleCopy is common method. The differences are, Bookclass has author and orderCopies(). Magazine
Class has methods orderQty, Current issue, receiveissue().Write a program to find how many copies of the given books are
ordered and display total sale of publication.

class Publication {

// Common instance variables protected String title; protected

double price; protected int copies; // Constructor for Publication

public Publication(String title, double price, int copies) {

this.title = title; this.price

= price; this.copies = copies;

// Method to calculate the total sale of copies public

void saleCopy(int numCopies) { this.copies -=

numCopies; double saleAmount = numCopies *

price;

System.out.println("Sale of " + numCopies + " copies of " + title + " generated: $" + saleAmount);

// Method to display the total sale of publication public

double getTotalSale(int numCopies) { return numCopies *

price;

}
// Book class inherits from Publication class Book extends Publication { private

String author; // Constructor for Book public Book(String title, String author,

double price, int copies) { super(title, price, copies); this.author =

author;

// Method to order copies of the book public void

orderCopies(int numCopies) {

System.out.println(numCopies + " copies of " + title + " by " + author + " ordered."); this.copies += numCopies;

}}

// Magazine class inherits from Publication class Magazine extends Publication { private int orderQty; //

Specific to Magazine private String currentIssue; // Constructor for Magazine public Magazine(String

title, String currentIssue, double price, int copies, int orderQty) { super(title, price, copies);

this.currentIssue = currentIssue; this.orderQty = orderQty;

// Method to order copies of the magazine public void

receiveIssue(String newIssue, int orderQty) { this.currentIssue =

newIssue; this.orderQty = orderQty; this.copies += orderQty;

System.out.println(orderQty + " copies of " + title + " for issue " + currentIssue + " received.");

}}

// Main class to test the program public class

PublicationTest { public static void

main(String[] args) {

// Create Book objects

Book book1 = new Book("Java Programming", "Author A", 40.50, 10);

Book book2 = new Book("Python Basics", "Author B", 35.75, 5);

// Create Magazine objects

Magazine magazine1 = new Magazine("Tech Monthly", "October 2024", 10.99, 50, 100);

Magazine magazine2 = new Magazine("Science Weekly", "Week 42 2024", 5.99, 30, 50);

// Order copies for books book1.orderCopies(20);

book2.orderCopies(15);

// Receive new issue for magazines

magazine1.receiveIssue("November 2024", 120);

magazine2.receiveIssue("Week 43 2024", 80); // Calculate

and display total sales for books book1.saleCopy(15); // Sale


15 copies of book1 book2.saleCopy(10); // Sale 10 copies of

book2

// Calculate total sales double totalSaleBook1 =

book1.getTotalSale(15); double totalSaleBook2 =

book2.getTotalSale(10);

// Display total sale for all publications

System.out.println("\nTotal sale for all publications:");

System.out.println("Total sale for book 1: $" + totalSaleBook1); System.out.println("Total sale for book 2:

$" + totalSaleBook2);

3.Design and develop inheritance for a given case study, identify objects and relationships and implement inheritance
wherever applicable. Employee class hasEmp_name, Emp_id, Address, Mail_id, and Mobile_noas members. Inherit the
classes: Programmer, Team Lead, Assistant Project Manager and Project Manager from employee class. Add Basic Pay (BP)
as the member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff
club fund. Generate pay slips for the employees withtheir gross and net salary.

class Employee {

// Common attributes

String empName; int

empId;

String address;

String mailId;

String mobileNo;

// Constructor to initialize employee details public Employee(String empName, int empId, String address, String

mailId, String mobileNo) { this.empName = empName; this.empId = empId; this.address = address;

this.mailId = mailId; this.mobileNo = mobileNo;

// Method to display employee details public void

displayEmployeeDetails() {

System.out.println("Employee Name: " + empName);

System.out.println("Employee ID: " + empId);

System.out.println("Address: " + address);

System.out.println("Mail ID: " + mailId);

System.out.println("Mobile No: " + mobileNo);

}
// Subclass Programmer inheriting from Employee class

Programmer extends Employee { double basicPay; //

Constructor

public Programmer(String empName, int empId, String address, String mailId, String mobileNo, double basicPay) {

super(empName, empId, address, mailId, mobileNo); this.basicPay =

basicPay;

// Method to generate pay slip for Programmer public void generatePaySlip() { double da = 0.97

* basicPay; // 97% of Basic Pay as DA double hra = 0.10 * basicPay; // 10% of Basic Pay as HRA

double pf = 0.12 * basicPay; // 12% of Basic Pay as PF double staffClubFund = 0.001 * basicPay; //

0.1% of Basic Pay as Staff Club Fund double grossSalary = basicPay + da + hra; // Gross Salary

double netSalary = grossSalary - pf - staffClubFund; // Net Salary

// Display pay slip details

System.out.println("\nPay Slip for Programmer:"); displayEmployeeDetails();

System.out.println("Basic Pay: " + basicPay);

System.out.println("DA: " + da);

System.out.println("HRA: " + hra);

System.out.println("PF: " + pf);

System.out.println("Staff Club Fund: " + staffClubFund);

System.out.println("Gross Salary: " + grossSalary);

System.out.println("Net Salary: " + netSalary);

// Subclass TeamLead inheriting from Employee class

TeamLead extends Employee { double basicPay; //

Constructor

public TeamLead(String empName, int empId, String address, String mailId, String mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo); this.basicPay = basicPay;

// Method to generate pay slip for Team Lead

public void generatePaySlip() { double da = 0.97 * basicPay; // 97% of Basic Pay as DA

double hra = 0.10 * basicPay; // 10% of Basic Pay as HRA double pf = 0.12 * basicPay; // 12% of

Basic Pay as PF double staffClubFund = 0.001 * basicPay; // 0.1% of Basic Pay as Staff Club Fund

double grossSalary = basicPay + da + hra; // Gross Salary double netSalary = grossSalary - pf -

staffClubFund; // Net Salary


// Display pay slip details

System.out.println("\nPay Slip for Team Lead:"); displayEmployeeDetails();

System.out.println("Basic Pay: " + basicPay);

System.out.println("DA: " + da);

System.out.println("HRA: " + hra);

System.out.println("PF: " + pf);

System.out.println("Staff Club Fund: " + staffClubFund);

System.out.println("Gross Salary: " + grossSalary);

System.out.println("Net Salary: " + netSalary);

}}

// Subclass AssistantProjectManager inheriting from Employee class

AssistantProjectManager extends Employee { double basicPay; //

Constructor

public AssistantProjectManager(String empName, int empId, String address, String mailId, String mobileNo, double
basicPay) { super(empName, empId, address, mailId, mobileNo); this.basicPay = basicPay;

// Method to generate pay slip for Assistant Project Manager public void

generatePaySlip() { double da = 0.97 * basicPay; // 97% of Basic Pay as

DA double hra = 0.10 * basicPay; // 10% of Basic Pay as HRA

double pf = 0.12 * basicPay; // 12% of Basic Pay as PF double

staffClubFund = 0.001 * basicPay; // 0.1% of Basic Pay as Staff Club Fund

double grossSalary = basicPay + da + hra; // Gross Salary double

netSalary = grossSalary - pf - staffClubFund; // Net Salary

// Display pay slip details

System.out.println("\nPay Slip for Assistant Project Manager:"); displayEmployeeDetails();

System.out.println("Basic Pay: " + basicPay);

System.out.println("DA: " + da);

System.out.println("HRA: " + hra);

System.out.println("PF: " + pf);

System.out.println("Staff Club Fund: " + staffClubFund);

System.out.println("Gross Salary: " + grossSalary);

System.out.println("Net Salary: " + netSalary);

}}
// Subclass ProjectManager inheriting from Employee class

ProjectManager extends Employee { double basicPay; //

Constructor

public ProjectManager(String empName, int empId, String address, String mailId, String mobileNo, double
basicPay) { super(empName, empId, address, mailId, mobileNo); this.basicPay = basicPay;

public void generatePaySlip() { double da = 0.97 * basicPay; // 97% of Basic Pay as DA

double hra = 0.10 * basicPay; // 10% of Basic Pay as HRA double pf = 0.12 * basicPay; // 12% of

Basic Pay as PF double staffClubFund = 0.001 * basicPay; // 0.1% of Basic Pay as Staff Club Fund

double grossSalary = basicPay + da + hra; // Gross Salary double netSalary = grossSalary - pf -

staffClubFund; // Net Salary

// Display pay slip details

System.out.println("\nPay Slip for Project Manager:");

displayEmployeeDetails();

System.out.println("Basic Pay: " + basicPay);

System.out.println("DA: " + da);

System.out.println("HRA: " + hra);

System.out.println("PF: " + pf);

System.out.println("Staff Club Fund: " + staffClubFund);

System.out.println("Gross Salary: " + grossSalary);

System.out.println("Net Salary: " + netSalary);

}}

public class EmployeeInheritance { public static

void main(String[] args) {

Programmer programmer = new Programmer("Alice", 101, "123 Main St", "alice@mail.com", "1234567890", 50000);

TeamLead teamLead = new TeamLead("Bob", 102, "456 Elm St", "bob@mail.com",


"0987654321", 70000); programmer.generatePaySlip();

teamLead.generatePaySlip();

4.Design a base class shape with two double type values and member functions to input the data and compute_area() for
calculating area of shape. Derive two classes: triangle and rectangle. Make compute_area() as abstract function and redefine
this function in the derived class to suit their requirements. Write a program that accepts dimensions of triangle/rectangle and
display calculated area.

abstract class Shape { protected

double dim1, dim2;


// Method to input data (dimensions) public void

inputData(double dim1, double dim2) { this.dim1 = dim1;

this.dim2 = dim2;

// Abstract method to compute area abstract public

void compute_area();

// Derived class Triangle class

Triangle extends Shape {

// Override compute_area() to calculate area of a triangle

@Override public void compute_area() { double area = 0.5 * dim1 * dim2;

// Formula: 1/2 * base * height

System.out.println("Area of the Triangle: " + area);

// Derived class Rectangle class

Rectangle extends Shape {

// Override compute_area() to calculate area of a rectangle

@Override public void

compute_area() { double area =

dim1 * dim2; // Formula: length *

breadth

System.out.println("Area of the Rectangle: " + area);

// Main class to test the program public class

ShapeAreaCalculator { public static void

main(String[] args) {

// Create base class reference and derived class objects

Shape shape;
// Create Triangle object and calculate area shape = new Triangle();

shape.inputData(10, 20); // For example, base = 10, height = 20 shape.compute_area(); //

Dynamic binding calls Triangle's compute_area()

// Create Rectangle object and calculate area shape = new Rectangle();

shape.inputData(15, 25); // For example, length = 15, breadth = 25 shape.compute_area(); //

Dynamic binding calls Rectangle's compute_area()

5.Design and develop a context for given case study and implement an interface for Vehicles Consider the example of
vehicles like bicycle, car and bike. All Vehicles have common functionalities such as Gear Change, Speed up and apply
breaks. Make an interface and put all these common functionalities. Bicycle, Bike, Car classes should be implemented for all
these functionalities in their own class in their way.
interface Vehicle {

void gearChange(int newGear); void speedUp(int increment);

void applyBrakes(int decrement);

// Bicycle class implementing the Vehicle interface class

Bicycle implements Vehicle { int speed; int gear;

// Constructor public

Bicycle() { this.speed

= 0; this.gear = 1;

// Implement the gearChange method public void

gearChange(int newGear) { gear = newGear;

System.out.println("Bicycle gear changed to: " + gear);

// Implement the speedUp method public void

speedUp(int increment) { speed += increment;

System.out.println("Bicycle speed increased to: " + speed);

// Implement the applyBrakes method public void

applyBrakes(int decrement) { speed -= decrement;

System.out.println("Bicycle speed decreased to: " + speed);

}
// Bike class implementing the Vehicle interface class Bike

implements Vehicle {

int speed; int

gear;

// Constructor public

Bike() { this.speed = 0;

this.gear = 1;

// Implement the gearChange method public void

gearChange(int newGear) { gear = newGear;

System.out.println("Bike gear changed to: " + gear);

// Implement the speedUp method public void

speedUp(int increment) { speed += increment;

System.out.println("Bike speed increased to: " + speed);

// Implement the applyBrakes method

public void applyBrakes(int decrement) { speed -=

decrement;

System.out.println("Bike speed decreased to: " + speed);

// Car class implementing the Vehicle interface class Car

implements Vehicle { int speed; int gear;

// Constructor public

Car() { this.speed = 0;

this.gear = 1;

// Implement the gearChange method public void

gearChange(int newGear) { gear = newGear;

System.out.println("Car gear changed to: " + gear);

// Implement the speedUp method public void

speedUp(int increment) { speed += increment;

System.out.println("Car speed increased to: " + speed);

}
// Implement the applyBrakes method public void

applyBrakes(int decrement) { speed -= decrement;

System.out.println("Car speed decreased to: " + speed);

// Main class to test the Vehicle interface and its implementations public class

Main { public static void main(String[] args) { // Bicycle instance

Vehicle bicycle = new Bicycle();

System.out.println("Testing Bicycle:");

bicycle.gearChange(2); bicycle.speedUp(10);

bicycle.applyBrakes(3);

// Bike instance

Vehicle bike = new Bike();

System.out.println("\nTesting Bike:");

bike.gearChange(3); bike.speedUp(20);

bike.applyBrakes(7);

// Car instance

Vehicle car = new Car();

System.out.println("\nTesting Car:");

car.gearChange(4); car.speedUp(50);

car.applyBrakes(15);

6) Implement a program to handle Arithmetic exception, Array Index Out of Bounds. The user enters two numbers Num1
and Num2. The division of Num1 and Num2 is displayed. If Num1 and Num2 are not integers, the program would throw a
Number Format Exception. If Num2 were zero, the program would throw an Arithmetic Exception. Display the exception.

import java.util.Scanner;

public class ExceptionHandlingDemo { public static

void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Array to demonstrate ArrayIndexOutOfBoundsException int[]

numbersArray = {1, 2, 3, 4, 5};

try {
// Taking input from the user for Num1 and Num2

System.out.print("Enter Num1 (integer): ");

String input1 = scanner.nextLine(); // Input as string to check for number format exception

System.out.print("Enter Num2 (integer): ");

String input2 = scanner.nextLine(); // Input as string to check for number format exception

// Parse the input to integers int num1

= Integer.parseInt(input1); int num2 =

Integer.parseInt(input2);

// Perform division and check for ArithmeticException int result

= num1 / num2;

System.out.println("Result of division: " + result);

// Accessing an invalid array index to demonstrate ArrayIndexOutOfBoundsException

System.out.println("Accessing invalid index in array: " + numbersArray[10]); // Invalid index

} catch (NumberFormatException e) {

// Handle case where input is not a valid integer

System.out.println("Error: Invalid input, please enter integers only. Exception: " + e);

} catch (ArithmeticException e) {

// Handle division by zero

System.out.println("Error: Division by zero is not allowed. Exception: " + e);

} catch (ArrayIndexOutOfBoundsException e) {

// Handle invalid array index access

System.out.println("Error: Array index out of bounds. Exception: " + e); } finally {

// Closing the scanner scanner.close();

System.out.println("Program execution completed.");

7. Implement a generic program using any collection class to count the number of elements in a collection that have a specific
property such as even numbers, odd number, prime number and palindromes.

import java.util.ArrayList;

import java.util.List;

import java.util.function.Predicate;

public class GenericCollectionProgram {


// Generic method to count elements that satisfy a certain condition public static <T> int

countByCondition(List<T> collection, Predicate<T> condition) {

int count = 0; for (T element :

collection) { if

(condition.test(element)) { count+

+;

} return

count;

// Method to check if a number is even public static

boolean isEven(Integer number) { return number % 2

== 0;

// Method to check if a number is odd public static

boolean isOdd(Integer number) { return number % 2 !

= 0;

// Method to check if a number is prime public static

boolean isPrime(Integer number) { if (number <= 1)

return false; for (int i = 2; i <= Math.sqrt(number); i++)

{ if (number % i == 0) return false;

} return

true;

// Method to check if a number (or string) is a palindrome public static

boolean isPalindrome(String str) {

int start = 0; int end = str.length() - 1;

while (start < end) { if (str.charAt(start) !=

str.charAt(end)) { return false;

start++;

end--; }

return true;

}
public static void main(String[] args) {

// List of numbers for testing even, odd, and prime conditions

List<Integer> numbers = new ArrayList<>(); numbers.add(2);

numbers.add(3); numbers.add(4); numbers.add(5);

numbers.add(11); numbers.add(13); numbers.add(20);

numbers.add(23);

// List of strings for palindrome checking

List<String> strings = new ArrayList<>();

strings.add("madam"); strings.add("racecar");

strings.add("hello"); strings.add("level");

strings.add("world");

// Counting even numbers int evenCount = countByCondition(numbers,

GenericCollectionProgram::isEven);

System.out.println("Even numbers count: " + evenCount);

// Counting odd numbers int oddCount = countByCondition(numbers,

GenericCollectionProgram::isOdd);

System.out.println("Odd numbers count: " + oddCount);

// Counting prime numbers int primeCount = countByCondition(numbers,

GenericCollectionProgram::isPrime);

System.out.println("Prime numbers count: " + primeCount);

// Counting palindromes in strings int palindromeCount = countByCondition(strings,

GenericCollectionProgram::isPalindrome); System.out.println("Palindrome strings count: " + palindromeCount);

8) Implement a program for maintaining a database of student records using Files. Student has Student_id,name, Roll_no,
Class, marks and address.Display the data for few students.

• Create Database • Display Database • Delete Records

• Update Record • Search Record

import java.io.*;

import java.util.*;

class Student implements Serializable { private static final long serialVersionUID

= 1L; // For serialization String studentId, name, rollNo, studentClass, address;

int marks;
public Student(String studentId, String name, String rollNo, String studentClass, int marks, String address)

{ this.studentId = studentId; this.name = name; this.rollNo = rollNo; this.studentClass = studentClass;

this.marks = marks; this.address = address;

@Override public String toString() { return "Student_id: " + studentId + ", Name: " + name +

", Roll_no: " + rollNo +

", Class: " + studentClass + ", Marks: " + marks + ", Address: " + address;

public class StudentDatabase {

private static final String FILE_NAME = "studentDatabase.txt";

// i) Create Database (Write to file)

public static void createDatabase(Student student) { try (FileOutputStream fos = new

FileOutputStream(FILE_NAME, true); ObjectOutputStream oos = new

ObjectOutputStream(fos)) { oos.writeObject(student);

System.out.println("Record added successfully.");

} catch (IOException e) {

System.out.println("Error while creating database: " + e.getMessage());

// ii) Display Database (Read from file) public static void displayDatabase() {

try (FileInputStream fis = new FileInputStream(FILE_NAME);

ObjectInputStream ois = new ObjectInputStream(fis)) {

boolean recordFound = false;

while (true) { try {

Student student = (Student) ois.readObject();

System.out.println(student); recordFound = true;

} catch (EOFException e) { break; // End of file reached

if (!recordFound) {

System.out.println("No records found.");

} catch (IOException | ClassNotFoundException e) {


System.out.println("Error while displaying database: " + e.getMessage()); }

// iii) Delete Record (Remove specific student record) public

static void deleteRecord(String studentId) { File tempFile = new

File("tempDatabase.txt");

File originalFile = new File(FILE_NAME);

try (FileInputStream fis = new FileInputStream(FILE_NAME); ObjectInputStream ois = new

ObjectInputStream(fis);

FileOutputStream fos = new FileOutputStream(tempFile);

ObjectOutputStream oos = new ObjectOutputStream(fos)) {

boolean recordDeleted = false;

while (true) {

try {

Student student = (Student) ois.readObject(); if

(!student.studentId.equals(studentId))

{ oos.writeObject(student);

} else

{ recordDeleted = true;

} catch (EOFException e)

{ break; // End of file

if (recordDeleted) {

System.out.println("Record deleted successfully.");

} else {

System.out.println("No record found with Student ID: " + studentId); }

// Replace the old file with the new one if (!originalFile.delete() || !

tempFile.renameTo(originalFile)) {

System.out.println("Error while updating file.");

} catch (IOException | ClassNotFoundException e) {

System.out.println("Error while deleting record: " + e.getMessage());

}
// iv) Update Record (Modify student details) public static void updateRecord(String

studentId, Student updatedStudent) {

File tempFile = new File("tempDatabase.txt");

File originalFile = new File(FILE_NAME);

try (FileInputStream fis = new FileInputStream(FILE_NAME); ObjectInputStream ois = new

ObjectInputStream(fis);

FileOutputStream fos = new FileOutputStream(tempFile);

ObjectOutputStream oos = new ObjectOutputStream(fos)) {

boolean recordUpdated = false;

while (true) {

try {

Student student = (Student) ois.readObject(); if

(!student.studentId.equals(studentId))

{ oos.writeObject(student);

} else {

oos.writeObject(updatedStudent); // Write updated student recordUpdated =true;

} catch (EOFException e)

{ break; // End of file

if (recordUpdated) {

System.out.println("Record updated successfully.");

} else {

System.out.println("No record found with Student ID: " + studentId);

// Replace the old file with the new one if (!originalFile.delete() || !

tempFile.renameTo(originalFile)) {

System.out.println("Error while updating file.");

} catch (IOException | ClassNotFoundException e) {

System.out.println("Error while updating record: " + e.getMessage());

}
// v) Search Record (Find student by ID or name) public static void

searchRecord(String searchTerm) { try (FileInputStream fis = new

FileInputStream(FILE_NAME);

ObjectInputStream ois = new ObjectInputStream(fis)) {

boolean recordFound = false;

while (true) {

try {

Student student = (Student) ois.readObject();

if (student.studentId.equals(searchTerm) || student.name.equalsIgnoreCase(searchTerm)) {

System.out.println("Record found: " + student);

recordFound = true; break;

} catch (EOFException e)

{ break; // End of file

if (!recordFound) {

System.out.println("No record found for search term: " + searchTerm);

} catch (IOException | ClassNotFoundException e) {

System.out.println("Error while searching record: " + e.getMessage());

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\n*** Student Database Menu ***");

System.out.println("1. Create Database");

System.out.println("2. Display Database");

System.out.println("3. Delete Record");

System.out.println("4. Update Record");

System.out.println("5. Search Record");

System.out.println("6. Exit");
System.out.print("Enter your choice: "); int

choice = scanner.nextInt(); scanner.nextLine();

//Consume newline

switch (choice)

{ case 1:

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

String studentId = scanner.nextLine();

System.out.print("Enter Name: ");

String name = scanner.nextLine();

System.out.print("Enter Roll No: ");

String rollNo = scanner.nextLine();

System.out.print("Enter Class: ");

String studentClass = scanner.nextLine();

System.out.print("Enter Marks: "); int marks =

scanner.nextInt(); scanner.nextLine(); // Consume

newline System.out.print("Enter Address: ");

String address = scanner.nextLine();

Student student = new Student(studentId, name, rollNo, studentClass, marks, address);

createDatabase(student); break;

case 2:

displayDatabase(); break;

case 3:

System.out.print("Enter Student ID to delete: ");

String deleteId = scanner.nextLine(); deleteRecord(deleteId);

break;

case 4:

System.out.print("Enter Student ID to update: ");

String updateId = scanner.nextLine();

System.out.print("Enter new Name: ");

String newName = scanner.nextLine();

System.out.print("Enter new Roll No: ");

String newRollNo = scanner.nextLine();

System.out.print("Enter new Class: ");


String newClass = scanner.nextLine();

System.out.print("Enter new Marks: "); int newMarks

= scanner.nextInt(); scanner.nextLine(); // Consume

newline

System.out.print("Enter new Address: ");

String newAddress = scanner.nextLine();

Student updatedStudent = new Student(updateId, newName, newRollNo, newClass, newMarks, newAddress);

updateRecord(updateId, updatedStudent);

break;

case 5:

System.out.print("Enter Student ID or Name to search: "); String

searchTerm = scanner.nextLine(); searchRecord(searchTerm);

break;

case 6:

System.out.println("Exiting...");

scanner.close(); return;

default:

System.out.println("Invalid choice! Please enter again.");

}}

9) Using concepts of Object-Oriented programming develop solution for anyone application 1) Banking system having
following operations :1. Create an account 2. Deposit money 3. Withdraw money 4. Honor daily
withdrawal limit 5. Check the

balance 6. Display Account

information

import java.util.Scanner;

// BankAccount class that encapsulates all the banking operations class

BankAccount { private String accountNumber; private String

accountHolder; private double balance; private double dailyLimit;

private double amountWithdrawnToday;

// Constructor to create an account

public BankAccount(String accountNumber, String accountHolder, double initialBalance, double dailyLimit)

{ this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.balance =

initialBalance; this.dailyLimit = dailyLimit; this.amountWithdrawnToday = 0.0;


}

// Method to deposit money public void

deposit(double amount) { if (amount > 0) {

balance += amount;

System.out.println("Deposit successful! New balance: $" + balance); } else {

System.out.println("Deposit amount should be positive.");

// Method to withdraw money public void

withdraw(double amount) { if (amount <= 0)

System.out.println("Withdrawal amount should be positive.");

} else if (amount > balance) {

System.out.println("Insufficient funds. Your balance is: $" + balance);

} else if ((amountWithdrawnToday + amount) > dailyLimit) {

System.out.println("Withdrawal amount exceeds daily limit of $" + dailyLimit);

} else { balance -= amount;

amountWithdrawnToday += amount;

System.out.println("Withdrawal successful! New balance: $" + balance);

// Method to check the balance public void

checkBalance() {

System.out.println("Current balance: $" + balance);

// Method to display account information public void

displayAccountInfo() {

System.out.println("Account Number: " + accountNumber);

System.out.println("Account Holder: " + accountHolder); System.out.println("Balance: $" + balance);

System.out.println("Daily Withdrawal Limit: $" + dailyLimit);

System.out.println("Amount Withdrawn Today: $" + amountWithdrawnToday);

// Method to reset the daily withdrawal limit (to be called at the end of the day) public void

resetDailyLimit() { amountWithdrawnToday = 0.0;


System.out.println("Daily withdrawal limit has been reset.");

// Main class to handle user interactions public

class Main { public static void main(String[]

args) {

Scanner scanner = new Scanner(System.in);

// Create a new bank account

System.out.print("Enter account number: ");

String accountNumber = scanner.nextLine();

System.out.print("Enter account holder name: ");

String accountHolder = scanner.nextLine();

System.out.print("Enter initial balance: "); double

initialBalance = scanner.nextDouble();

System.out.print("Enter daily withdrawal limit: "); double

dailyLimit = scanner.nextDouble();

BankAccount account = new BankAccount(accountNumber, accountHolder, initialBalance, dailyLimit);

boolean running = true; while

(running) {

System.out.println("\n1. Deposit money");

System.out.println("2. Withdraw money");

System.out.println("3. Check balance");

System.out.println("4. Display account information");

System.out.println("5. Reset daily withdrawal limit");

System.out.println("6. Exit");

System.out.print("Choose an option: "); int

choice = scanner.nextInt();

switch (choice)

{ case 1:

System.out.print("Enter deposit amount: "); double

depositAmount = scanner.nextDouble();

account.deposit(depositAmount);

break;

case2:
System.out.print("Enter withdrawal amount: "); double

withdrawAmount = scanner.nextDouble();

account.withdraw(withdrawAmount);

break;

case3:

account.checkBalance();

break;

case4:

account.displayAccountInfo();

break;

case5:

account.resetDailyLimit();

break;

case6:

running = false;

System.out.println("Exiting the system...");

break;

default:

System.out.println("Invalid option. Please try again."); break;

scanner.close();

10) Implement Factory design pattern for the given context. Consider Car building process, which requires many steps from
allocating accessories to final makeup. These steps should be written as methods and should be called
while creating an instance of a specific car type. Hatchback, Sedan, SUV could be the subclasses of Car class. Car class and
its subclasses, CarFactory and Test Factory Pattern should be implemented.

abstract class Car { public abstract void

assemble(); public abstract void

addAccessories(); public abstract void

finalMakeup(); public void buildCar()

{ assemble(); addAccessories();

finalMakeup();

}
class Hatchback extends Car { public void

assemble() {

System.out.println("Assembling Hatchback car body, engine, and components...");

public void addAccessories() {

System.out.println("Adding basic Hatchback accessories (radio, air conditioning)...");

public void finalMakeup() {

System.out.println("Giving final makeup to Hatchback car (painting, polishing)...");

class Sedan extends Car {

@Override public void

assemble() {

System.out.println("Assembling Sedan car body, engine, and components...");

public void addAccessories() {

System.out.println("Adding premium Sedan accessories (leather seats, sunroof, touchscreen)..."); }

public void finalMakeup() {

System.out.println("Giving final makeup to Sedan car (painting, polishing)...");

}}

class SUV extends Car { public

void assemble() {

System.out.println("Assembling SUV car body, engine, and components...");

public void addAccessories() {

System.out.println("Adding luxury SUV accessories (GPS, high-quality sound system, off-road tires)...");

public void finalMakeup() {

System.out.println("Giving final makeup to SUV car (painting, polishing)...");

}}

class CarFactory { public static Car createCar(String

carType) { if (carType == null || carType.isEmpty())

{ return null;
}

if ("Hatchback".equalsIgnoreCase(carType)) { return new

Hatchback();

} else if ("Sedan".equalsIgnoreCase(carType)) { return new

Sedan();

} else if ("SUV".equalsIgnoreCase(carType)) { return new

SUV();

} return

null;

}}

public class TestFactoryPattern { public static

void main(String[] args) {

Car hatchback = CarFactory.createCar("Hatchback"); if

(hatchback != null) {

System.out.println("\nBuilding a Hatchback car:"); hatchback.buildCar();

Car sedan = CarFactory.createCar("Sedan"); if

(sedan != null) {

System.out.println("\nBuilding a Sedan car:"); sedan.buildCar();

Car suv = CarFactory.createCar("SUV");

if (suv != null) {

System.out.println("\nBuilding an SUV car:"); suv.buildCar();

} }}

11) Write a program that prompts the user for a password and raises an AuthenticationFailure exception if the entered
password is incorrect.
import java.util.Scanner;

// Custom exception class


class AuthenticationFailure extends Exception {
public AuthenticationFailure(String message) {
super(message); }}

// Main class with authentication method


public class Main {
// Method to authenticate user
public static void authenticate(String password) throws AuthenticationFailure {
String correctPassword = "securepassword"; // Set the correct password here

if (!password.equals(correctPassword)) {
// Throw custom exception if the password is incorrect
throw new AuthenticationFailure("Authentication failed: Incorrect password");
} else {
System.out.println("Authentication successful!");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter your password: ");


String userPassword = scanner.nextLine();

try {
authenticate(userPassword);
} catch (AuthenticationFailure e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
} }}

12) Write a program to check of candidate, if the age is less than 18 throw ‘AgeExceptionFailure’ exception else allow
candidate for voting.

import java.util.Scanner;

// Custom exception class


class AgeExceptionFailure extends Exception {
public AgeExceptionFailure(String message) {
super(message);
}
}

// Main class
public class Main {
// Method to check if the candidate is eligible to vote
public static void checkVotingEligibility(int age) throws AgeExceptionFailure {
if (age < 18) {
// Throw custom exception if age is less than 18
throw new AgeExceptionFailure("AgeExceptionFailure: Candidate is under 18 and not eligible to vote.");
} else {
System.out.println("Candidate is eligible to vote.");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter candidate's age: ");


int age = scanner.nextInt();

try {
checkVotingEligibility(age);
} catch (AgeExceptionFailure e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}}
13) Define a Student class with four attributes: name, roll_no, sub1, and sub2.Include methods to initialize and display the
values of these attributes, and also calculate the total marks and percentage based on three subjects..

// Student class definition


class Student {
// Attributes of the Student class
private String name;
private int roll_no;
private int sub1, sub2, sub3;

// Constructor to initialize the Student attributes


public Student(String name, int roll_no, int sub1, int sub2, int sub3) {
this.name = name;
this.roll_no = roll_no;
this.sub1 = sub1;
this.sub2 = sub2;
this.sub3 = sub3;
}

// Method to calculate the total marks


public int calculateTotal() {
return sub1 + sub2 + sub3;
}

// Method to calculate the percentage


public float calculatePercentage() {
return calculateTotal() / 3.0f; // Assuming each subject is out of 100
}

// Method to display student information and marks


public void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + roll_no);
System.out.println("Marks in Subject 1: " + sub1);
System.out.println("Marks in Subject 2: " + sub2);
System.out.println("Marks in Subject 3: " + sub3);
System.out.println("Total Marks: " + calculateTotal());
System.out.println("Percentage: " + calculatePercentage() + "%");
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating a Student object and initializing attributes
Student student = new Student("Alice", 101, 85, 90, 95);

// Displaying the details and marks of the student


student.displayDetails();
}
}

14) Implement a LinkedList program that:


• Adds elements to the list • Inserts elements at specific positions
• Removes elements based on their value • Returns the current size of the list

import java.util.LinkedList;

public class CustomLinkedList {


private LinkedList<Integer> list; // Using Integer for simplicity, can be any type

// Constructor
public CustomLinkedList() {
list = new LinkedList<>();
}

// Method to add an element to the list


public void addElement(int element) {
list.add(element);
System.out.println(element + " added to the list.");
}

// Method to insert an element at a specific position


public void insertElement(int index, int element) {
if (index < 0 || index > list.size()) {
System.out.println("Invalid index. Element not inserted.");
return;
}
list.add(index, element);
System.out.println(element + " inserted at position " + index + ".");
}

// Method to remove an element based on its value


public void removeElement(int element) {
if (list.remove(Integer.valueOf(element))) {
System.out.println(element + " removed from the list.");
} else {
System.out.println(element + " not found in the list.");
}
}

// Method to get the current size of the list


public int getSize() {
return list.size();
}

// Method to display all elements in the list


public void displayList() {
System.out.println("Current List: " + list);
}

// Main method to demonstrate the functionality


public static void main(String[] args) {
CustomLinkedList customList = new CustomLinkedList();

// Adding elements
customList.addElement(10);
customList.addElement(20);
customList.addElement(30);
customList.displayList();

// Inserting elements at specific positions


customList.insertElement(1, 15); // Insert 15 at index 1
customList.insertElement(0, 5); // Insert 5 at index 0
customList.displayList();

// Removing an element by value


customList.removeElement(20); // Remove element with value 20
customList.displayList();

// Checking the size of the list


System.out.println("Current size of the list: " + customList.getSize());
}
}
15) Write a program using an ArrayList to:
• Add elements to the list • Insert elements at specific positions
• Remove elements based on their value • Check whether the list is empty

import java.util.ArrayList;
public class CustomArrayList {
private ArrayList<Integer> list;

// Constructor
public CustomArrayList() {
list = new ArrayList<>();
}

// Method to add an element to the list


public void addElement(int element) {
list.add(element);
System.out.println(element + " added to the list.");
}

// Method to insert an element at a specific position


public void insertElement(int index, int element) {
if (index < 0 || index > list.size()) {
System.out.println("Invalid index. Element not inserted.");
return;
}
list.add(index, element);
System.out.println(element + " inserted at position " + index + ".");
}

// Method to remove an element based on its value


public void removeElement(int element) {
if (list.remove(Integer.valueOf(element))) {
System.out.println(element + " removed from the list.");
} else {
System.out.println(element + " not found in the list.");
}
}

// Method to check if the list is empty


public boolean isEmpty() {
return list.isEmpty();
}

// Method to display all elements in the list


public void displayList() {
System.out.println("Current List: " + list);
}

// Main method to demonstrate the functionality


public static void main(String[] args) {
CustomArrayList customList = new CustomArrayList();

// Adding elements
customList.addElement(10);
customList.addElement(20);
customList.addElement(30);
customList.displayList();

// Inserting elements at specific positions


customList.insertElement(1, 15); // Insert 15 at index 1
customList.insertElement(0, 5); // Insert 5 at index 0
customList.displayList();

// Removing an element by value


customList.removeElement(20); // Remove element with value 20
customList.displayList();
// Checking if the list is empty
System.out.println("Is the list empty? " + customList.isEmpty());
}
}

16) Implement a multi-level inheritance structure with three classes:


• Account: Contains Cust_name and acc_no.
• Saving_Account: Inherits from Account and includes Min_bal and
saving_bal.
• Acct_Details: Inherits from Saving_Acc and adds Deposits and
withdrawals attributes.

// Base class
class Account {
protected String cust_name;
protected int acc_no;

// Constructor for Account class


public Account(String cust_name, int acc_no) {
this.cust_name = cust_name;
this.acc_no = acc_no;
}

// Method to display account information


public void displayAccountInfo() {
System.out.println("Customer Name: " + cust_name);
System.out.println("Account Number: " + acc_no);
}
}

// Derived class from Account


class Saving_Account extends Account {
protected double min_bal;
protected double saving_bal;

// Constructor for Saving_Account class


public Saving_Account(String cust_name, int acc_no, double min_bal, double saving_bal) {
super(cust_name, acc_no); // Call to parent constructor
this.min_bal = min_bal;
this.saving_bal = saving_bal;
}

// Method to display saving account information


public void displaySavingAccountInfo() {
displayAccountInfo(); // Call to Account method
System.out.println("Minimum Balance: " + min_bal);
System.out.println("Saving Account Balance: " + saving_bal);
}
}

// Derived class from Saving_Account


class Acct_Details extends Saving_Account {
private double deposits;
private double withdrawals;

// Constructor for Acct_Details class


public Acct_Details(String cust_name, int acc_no, double min_bal, double saving_bal, double deposits, double
withdrawals) {
super(cust_name, acc_no, min_bal, saving_bal); // Call to Saving_Account constructor
this.deposits = deposits;
this.withdrawals = withdrawals;
}
// Method to update balance after deposit
public void deposit(double amount) {
saving_bal += amount;
deposits += amount;
System.out.println("Deposited: " + amount);
System.out.println("New Balance: " + saving_bal);
}

// Method to update balance after withdrawal


public void withdraw(double amount) {
if (saving_bal - amount >= min_bal) {
saving_bal -= amount;
withdrawals += amount;
System.out.println("Withdrew: " + amount);
System.out.println("New Balance: " + saving_bal);
} else {
System.out.println("Insufficient funds to maintain minimum balance.");
}
}

// Method to display account details including deposits and withdrawals


public void displayAccountDetails() {
displaySavingAccountInfo(); // Call to Saving_Account method
System.out.println("Total Deposits: " + deposits);
System.out.println("Total Withdrawals: " + withdrawals);
}
}

// Main class to test the multi-level inheritance


public class Main {
public static void main(String[] args) {
// Create an Acct_Details object
Acct_Details account = new Acct_Details("John Doe", 123456, 500.0, 1500.0, 0.0, 0.0);

// Display initial account details


account.displayAccountDetails();

// Perform some transactions


account.deposit(200.0);
account.withdraw(100.0);
account.withdraw(2000.0); // Attempt to withdraw more than the balance

// Display final account details


account.displayAccountDetails();
}
}

17) Create an Employee class with attributes empID, name, salary, andexperience. Use an array of objects to store and display
these employee details.

import java.util.Scanner;

// Employee class
class Employee {
private int empID;
private String name;
private double salary;
private int experience;

// Constructor to initialize employee attributes


public Employee(int empID, String name, double salary, int experience) {
this.empID = empID;
this.name = name;
this.salary = salary;
this.experience = experience;
}

// Method to display employee details


public void displayDetails() {
System.out.println("Employee ID: " + empID);
System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
System.out.println("Experience: " + experience + " years");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of employees: ");


int numEmployees = scanner.nextInt();
scanner.nextLine(); // Consume newline

// Array to hold Employee objects


Employee[] employees = new Employee[numEmployees];

// Input employee details


for (int i = 0; i < numEmployees; i++) {
System.out.println("\nEnter details for Employee " + (i + 1) + ":");
System.out.print("Employee ID: ");
int empID = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Salary: ");
double salary = scanner.nextDouble();
System.out.print("Experience (in years): ");
int experience = scanner.nextInt();
scanner.nextLine(); // Consume newline

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


employees[i] = new Employee(empID, name, salary, experience);
}

// Display all employee details


System.out.println("\nEmployee Details:");
for (Employee employee : employees) {
employee.displayDetails();
System.out.println("----------");
}

scanner.close();
}
}
18) Consider a class Student having data members name, marks of three subjects,average and member function printDetails().
Take input of 3 students from user using array of objects and print it.

import java.util.Scanner;
// Student class definition
class Student {
private String name;
private int[] marks = new int[3]; // Array to store marks of three subjects
private double average;
// Constructor to initialize the name and marks of the student
public Student(String name, int mark1, int mark2, int mark3) {
this.name = name;
this.marks[0] = mark1;
this.marks[1] = mark2;
this.marks[2] = mark3;
this.calculateAverage();
}
// Method to calculate average marks
private void calculateAverage() {
int total = 0;
for (int mark : marks) {
total += mark;
}
this.average = total / 3.0;
}
// Method to print student details
public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks[0] + ", " + marks[1] + ", " + marks[2]);
System.out.println("Average: " + average);
}}
// Main class to handle input and display output
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[3]; // Array to hold 3 Student objects
// Input student details
for (int i = 0; i < students.length; i++) {
System.out.println("Enter details for Student " + (i + 1) + ":");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Marks in subject 1: ");
int mark1 = scanner.nextInt();
System.out.print("Marks in subject 2: ");
int mark2 = scanner.nextInt();
System.out.print("Marks in subject 3: ");
int mark3 = scanner.nextInt();
scanner.nextLine(); // Consume the newline
// Create a new Student object and store it in the array
students[i] = new Student(name, mark1, mark2, mark3);
}

// Display details of all students


System.out.println("\nStudent Details:");
for (Student student : students) {
student.printDetails();
System.out.println("----------");
}

scanner.close();
}
}
19) Design classes for "Android," "iOS," and "BlackBerry" that implement an "OS" interface with a "spec()" method to
display OS specifications. Utilize the factory design pattern to create a class that generates instances of these OS classes
based on user input and calls the appropriate "spec()" method..

import java.util.Scanner;
// OS Interface - Defines the method for all operating systems
interface OS {
void spec(); // Method to display the OS specifications
}
// Concrete class for Android OS
class Android implements OS {
@Override
public void spec() {
System.out.println("Android OS: Open-source, customizable, and used by multiple device manufacturers.");
}}
// Concrete class for iOS
class iOS implements OS {
@Override
public void spec() {
System.out.println("iOS: Apple's proprietary mobile OS, known for its security and smooth user experience.");
}}
// Concrete class for BlackBerry OS
class BlackBerry implements OS {
@Override
public void spec() {
System.out.println("BlackBerry OS: Formerly popular, known for its physical keyboards and security features.");
}}
// Factory class for creating OS objects based on user input
class OSFactory {
public OS getOS(String osType) {
if (osType == null) {
return null;
}
if (osType.equalsIgnoreCase("Android")) {
return new Android(); // Return Android OS instance
} else if (osType.equalsIgnoreCase("iOS")) {
return new iOS(); // Return iOS OS instance
} else if (osType.equalsIgnoreCase("BlackBerry")) {
return new BlackBerry(); // Return BlackBerry OS instance
}
return null; // Return null if input is invalid
}
}
// Main class that demonstrates the Factory pattern and interacts with the user
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Scanner for user input
OSFactory osFactory = new OSFactory(); // Create OSFactory instance
// Prompt user for OS choice
System.out.print("Enter the OS (Android, iOS, or BlackBerry): ");
String osType = scanner.nextLine(); // Read the user's input
// Use the factory to get the appropriate OS object
OS os = osFactory.getOS(osType);
// If a valid OS object is returned, call the spec() method
if (os != null) {
os.spec();
} else {
System.out.println("Invalid OS type. Please choose from Android, iOS, or BlackBerry.");
}

scanner.close(); // Close the scanner


}}
20) Define an interface OnlineCourse with a getDetails() method to display course details. Create classes for Python, Data
Structures, and Java courses. Apply thefactory design pattern to create a class that returns details for a specific online course
based on user selection.

import java.util.Scanner;
// OnlineCourse Interface - Defines a method to display course details
interface OnlineCourse {
void getDetails(); // Method to display course details
}

// Concrete class for Python Course


class PythonCourse implements OnlineCourse {
@Override
public void getDetails() {
System.out.println("Python Course: Learn Python programming from basics to advanced. Includes practical examples,
exercises, and real-world projects.");
}
}

// Concrete class for Data Structures Course


class DataStructuresCourse implements OnlineCourse {
@Override
public void getDetails() {
System.out.println("Data Structures Course: Covers topics like arrays, linked lists, stacks, queues, trees, graphs, and
algorithms.");
}
}

// Concrete class for Java Course


class JavaCourse implements OnlineCourse {
@Override
public void getDetails() {
System.out.println("Java Course: Learn Java programming from object-oriented basics to advanced topics like
multithreading, exception handling, and Java collections.");
}
}

// Factory class to return the appropriate OnlineCourse based on user input


class CourseFactory {
public OnlineCourse getCourse(String courseName) {
if (courseName == null) {
return null;
}

// Return the corresponding course object based on user input


if (courseName.equalsIgnoreCase("Python")) {
return new PythonCourse();
} else if (courseName.equalsIgnoreCase("DataStructures")) {
return new DataStructuresCourse();
} else if (courseName.equalsIgnoreCase("Java")) {
return new JavaCourse();
}

return null; // Return null if the course is invalid


}
}

// Main class to demonstrate the Factory design pattern


public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Scanner for user input
CourseFactory courseFactory = new CourseFactory(); // Create the CourseFactory

// Ask the user for a course name


System.out.print("Enter the course name (Python, DataStructures, or Java): ");
String courseName = scanner.nextLine(); // Read user input
// Use the factory to get the corresponding course object
OnlineCourse course = courseFactory.getCourse(courseName);

// If the course object is valid, call the getDetails() method to display course details
if (course != null) {
course.getDetails();
} else {
System.out.println("Invalid course name. Please choose from Python, DataStructures, or Java.");
}

scanner.close(); // Close the scanner


}
}

21) Develop a Calculator class with an add() method. Overload the "add()"method three times to handle different
combinations of input parameters(e.g., adding two integers, three integers, or two floating-point numbers).

public class Calculator {

// Add method for adding two integers


public int add(int a, int b) {
return a + b;
}

// Add method for adding three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Add method for adding two floating-point numbers


public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calculator = new Calculator(); // Create a Calculator object

// Test the add() method with two integers


int sum1 = calculator.add(5, 10);
System.out.println("Sum of 5 and 10 (integers): " + sum1);

// Test the add() method with three integers


int sum2 = calculator.add(3, 6, 9);
System.out.println("Sum of 3, 6, and 9 (integers): " + sum2);

// Test the add() method with two floating-point numbers


double sum3 = calculator.add(3.5, 4.5);
System.out.println("Sum of 3.5 and 4.5 (floating-point numbers): " + sum3);
}
}

22) Create a "Bank" class with a method to get the interest rate. Implement subclasses for "SBI," "ICICI," and "AXIS" banks,
each overriding the interest rate method to return their specific rates (e.g., 8%, 7%, and 9%, respectively).

// Base class
class Bank {
// Method to get the rate of interest
public float getRateOfInterest() {
return 0.0f; // Default interest rate
}
}

// Subclass for SBI


class SBI extends Bank {
// Overridden method to return SBI's interest rate
@Override
public float getRateOfInterest() {
return 8.0f; // SBI interest rate is 8%
}
}

// Subclass for ICICI


class ICICI extends Bank {
// Overridden method to return ICICI's interest rate
@Override
public float getRateOfInterest() {
return 7.0f; // ICICI interest rate is 7%
}
}

// Subclass for AXIS


class AXIS extends Bank {
// Overridden method to return AXIS's interest rate
@Override
public float getRateOfInterest() {
return 9.0f; // AXIS interest rate is 9%
}
}

// Main class to demonstrate the implementation


public class Main {
public static void main(String[] args) {
// Creating objects of each bank
Bank sbi = new SBI();
Bank icici = new ICICI();
Bank axis = new AXIS();

// Printing the interest rates of each bank


System.out.println("SBI Rate of Interest: " + sbi.getRateOfInterest() + "%");
System.out.println("ICICI Rate of Interest: " + icici.getRateOfInterest() + "%");
System.out.println("AXIS Rate of Interest: " + axis.getRateOfInterest() + "%");
}
}

23) Create a Java application that models animals capable of both walking and swimming, using interfaces to define these
behaviors. Implement classes for animals like Duck, Frog, Turtle, and Penguin, each providing specific implementations of
walk() and swim() methods. Write a Main class to instantiate these animals and demonstrate their behaviors by calling the
respective methods

// Walkable Interface - Defines walking behavior


interface Walkable {
void walk();
}

// Swimmable Interface - Defines swimming behavior


interface Swimmable {
void swim();
}
// Duck class implements both Walkable and Swimmable interfaces
class Duck implements Walkable, Swimmable {
@Override
public void walk() {
System.out.println("Duck is walking on land.");
}

@Override
public void swim() {
System.out.println("Duck is swimming in the water.");
}
}

// Frog class implements both Walkable and Swimmable interfaces


class Frog implements Walkable, Swimmable {
@Override
public void walk() {
System.out.println("Frog is hopping on land.");
}

@Override
public void swim() {
System.out.println("Frog is swimming in the pond.");
}
}

// Turtle class implements both Walkable and Swimmable interfaces


class Turtle implements Walkable, Swimmable {
@Override
public void walk() {
System.out.println("Turtle is walking slowly on land.");
}

@Override
public void swim() {
System.out.println("Turtle is swimming in the water.");
}
}

// Penguin class implements both Walkable and Swimmable interfaces


class Penguin implements Walkable, Swimmable {
@Override
public void walk() {
System.out.println("Penguin is waddling on land.");
}

@Override
public void swim() {
System.out.println("Penguin is swimming in the icy waters.");
}
}

// Main class to test the behavior of different animals


public class Main {
public static void main(String[] args) {
// Instantiate animals
Walkable duckWalk = new Duck();
Swimmable duckSwim = new Duck();

Walkable frogWalk = new Frog();


Swimmable frogSwim = new Frog();
Walkable turtleWalk = new Turtle();
Swimmable turtleSwim = new Turtle();

Walkable penguinWalk = new Penguin();


Swimmable penguinSwim = new Penguin();

// Demonstrate behaviors of each animal


System.out.println("Duck:");
duckWalk.walk();
duckSwim.swim();

System.out.println("\nFrog:");
frogWalk.walk();
frogSwim.swim();

System.out.println("\nTurtle:");
turtleWalk.walk();
turtleSwim.swim();

System.out.println("\nPenguin:");
penguinWalk.walk();
penguinSwim.swim();
}
}

24) Create a Student class with abstract methods to retrieve the student's name, SSC marks, and HSC marks. Then, create
three classes named Harish, Jayant, and Vijay that inherit from the Student class. Implement the abstract methods in each of
these subclasses to provide specific details for each student. Finally, print the details of each student.

// Abstract Student Class


abstract class Student {
// Abstract methods to get student details
public abstract String getName();
public abstract int getSSCMarks();
public abstract int getHSCMarks();
}

// Harish class inheriting from Student


class Harish extends Student {
@Override
public String getName() {
return "Harish";
}

@Override
public int getSSCMarks() {
return 85; // Example SSC marks for Harish
}

@Override
public int getHSCMarks() {
return 90; // Example HSC marks for Harish
}
}

// Jayant class inheriting from Student


class Jayant extends Student {
@Override
public String getName() {
return "Jayant";
}
@Override
public int getSSCMarks() {
return 78; // Example SSC marks for Jayant
}

@Override
public int getHSCMarks() {
return 88; // Example HSC marks for Jayant
}
}

// Vijay class inheriting from Student


class Vijay extends Student {
@Override
public String getName() {
return "Vijay";
}

@Override
public int getSSCMarks() {
return 92; // Example SSC marks for Vijay
}

@Override
public int getHSCMarks() {
return 87; // Example HSC marks for Vijay
}
}

// Main class to display student details


public class Main {
public static void main(String[] args) {
// Create objects for each student
Student harish = new Harish();
Student jayant = new Jayant();
Student vijay = new Vijay();

// Print details for each student


System.out.println("Student: " + harish.getName());
System.out.println("SSC Marks: " + harish.getSSCMarks());
System.out.println("HSC Marks: " + harish.getHSCMarks());
System.out.println();

System.out.println("Student: " + jayant.getName());


System.out.println("SSC Marks: " + jayant.getSSCMarks());
System.out.println("HSC Marks: " + jayant.getHSCMarks());
System.out.println();

System.out.println("Student: " + vijay.getName());


System.out.println("SSC Marks: " + vijay.getSSCMarks());
System.out.println("HSC Marks: " + vijay.getHSCMarks());
}
}

25) Design an "Animal" class with attributes for eats, noOfLegs, and isVeg. Implement getter and setter methods for each of
these attributes. Create a "Cat" class that inherits from "Animal" and adds a "skinColour" attribute. Use the super keyword in
the "Cat" class to access and print all four attributes (eats, noOfLegs, isVeg, and skinColour).
// Animal class with attributes and getter/setter methods
class Animal {
private String eats;
private int noOfLegs;
private boolean isVeg;

// Getter and Setter for eats


public String getEats() {
return eats;
}

public void setEats(String eats) {


this.eats = eats;
}

// Getter and Setter for noOfLegs


public int getNoOfLegs() {
return noOfLegs;
}

public void setNoOfLegs(int noOfLegs) {


this.noOfLegs = noOfLegs;
}

// Getter and Setter for isVeg


public boolean isVeg() {
return isVeg;
}

public void setVeg(boolean isVeg) {


this.isVeg = isVeg;
}
}

// Cat class inherits from Animal class and adds skinColour attribute
class Cat extends Animal {
private String skinColour;

// Getter and Setter for skinColour


public String getSkinColour() {
return skinColour;
}

public void setSkinColour(String skinColour) {


this.skinColour = skinColour;
}

// Method to print all attributes using super to access Animal class attributes
public void printAttributes() {
System.out.println("Eats: " + getEats());
System.out.println("Number of Legs: " + getNoOfLegs());
System.out.println("Is Vegetarian: " + isVeg());
System.out.println("Skin Colour: " + getSkinColour());
}
}

// Main class to test the functionality


public class Main {
public static void main(String[] args) {
// Create a Cat object
Cat cat = new Cat();

// Set attributes for the Cat object


cat.setEats("Fish");
cat.setNoOfLegs(4);
cat.setVeg(false);
cat.setSkinColour("Black");

// Print all attributes using the printAttributes method


cat.printAttributes();
}
}

26) Define an interface named "Area" with a method called calculateArea(). Implement this interface in separate classes for
Square, "Circle," "Triangle," and Rectangle. In each class, provide the specific implementation of the calculateArea() method
to calculate the area of the respective shape.

// Interface Area with the method calculateArea()


interface Area {
double calculateArea(); // Method to calculate area
}

// Square class implementing the Area interface


class Square implements Area {
private double side;

// Constructor to initialize the side of the square


public Square(double side) {
this.side = side;
}

// Implementing the calculateArea method for Square


@Override
public double calculateArea() {
return side * side; // Area of square = side^2
}
}

// Circle class implementing the Area interface


class Circle implements Area {
private double radius;

// Constructor to initialize the radius of the circle


public Circle(double radius) {
this.radius = radius;
}

// Implementing the calculateArea method for Circle


@Override
public double calculateArea() {
return Math.PI * radius * radius; // Area of circle = π * radius^2
}
}

// Triangle class implementing the Area interface


class Triangle implements Area {
private double base;
private double height;

// Constructor to initialize the base and height of the triangle


public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

// Implementing the calculateArea method for Triangle


@Override
public double calculateArea() {
return 0.5 * base * height; // Area of triangle = 0.5 * base * height
}
}

// Rectangle class implementing the Area interface


class Rectangle implements Area {
private double length;
private double width;

// Constructor to initialize the length and width of the rectangle


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Implementing the calculateArea method for Rectangle


@Override
public double calculateArea() {
return length * width; // Area of rectangle = length * width
}
}

// Main class to test the functionality


public class Main {
public static void main(String[] args) {
// Create objects for each shape
Square square = new Square(5);
Circle circle = new Circle(7);
Triangle triangle = new Triangle(4, 6);
Rectangle rectangle = new Rectangle(8, 3);

// Display the areas of each shape


System.out.println("Area of Square: " + square.calculateArea());
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy