Name1
Name1
public Complex() {
this.real = 0; this.imag
= 0; }
= imag; }
// Method for adding two complex numbers public Complex add(Complex other)
other.imag); }
Complex(realPart, imagPart); }
""; }
+ c2);
// Addition
// Subtraction
// Multiplication
// Division
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 {
price;
System.out.println("Sale of " + numCopies + " copies of " + title + " generated: $" + saleAmount);
price;
}
// Book class inherits from Publication class Book extends Publication { private
String author; // Constructor for Book public Book(String title, String author,
author;
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);
System.out.println(orderQty + " copies of " + title + " for issue " + currentIssue + " received.");
}}
main(String[] args) {
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);
book2.orderCopies(15);
book2
book2.getTotalSale(10);
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
empId;
String address;
String mailId;
String mobileNo;
// Constructor to initialize employee details public Employee(String empName, int empId, String address, String
displayEmployeeDetails() {
}
// Subclass Programmer inheriting from Employee class
Constructor
public Programmer(String empName, int empId, String address, String mailId, String mobileNo, double 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
Constructor
public TeamLead(String empName, int empId, String address, String mailId, String mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo); this.basicPay = basicPay;
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
}}
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
}}
// Subclass ProjectManager inheriting from Employee class
Constructor
public ProjectManager(String empName, int empId, String address, String mailId, String mobileNo, double
basicPay) { super(empName, empId, address, mailId, mobileNo); this.basicPay = basicPay;
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
displayEmployeeDetails();
}}
Programmer programmer = new Programmer("Alice", 101, "123 Main St", "alice@mail.com", "1234567890", 50000);
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.
this.dim2 = dim2;
void compute_area();
breadth
main(String[] args) {
Shape shape;
// Create Triangle object and calculate area shape = new Triangle();
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 {
// Constructor public
Bicycle() { this.speed
= 0; this.gear = 1;
}
// Bike class implementing the Vehicle interface class Bike
implements Vehicle {
gear;
// Constructor public
Bike() { this.speed = 0;
this.gear = 1;
decrement;
// Constructor public
Car() { this.speed = 0;
this.gear = 1;
}
// Implement the applyBrakes method public void
// Main class to test the Vehicle interface and its implementations public class
System.out.println("Testing Bicycle:");
bicycle.gearChange(2); bicycle.speedUp(10);
bicycle.applyBrakes(3);
// Bike instance
System.out.println("\nTesting Bike:");
bike.gearChange(3); bike.speedUp(20);
bike.applyBrakes(7);
// Car instance
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;
try {
// Taking input from the user for Num1 and Num2
String input1 = scanner.nextLine(); // Input as string to check for number format exception
String input2 = scanner.nextLine(); // Input as string to check for number format exception
Integer.parseInt(input2);
= num1 / num2;
} catch (NumberFormatException e) {
System.out.println("Error: Invalid input, please enter integers only. Exception: " + e);
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
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;
collection) { if
(condition.test(element)) { count+
+;
} return
count;
== 0;
= 0;
} return
true;
start++;
end--; }
return true;
}
public static void main(String[] args) {
numbers.add(23);
strings.add("madam"); strings.add("racecar");
strings.add("hello"); strings.add("level");
strings.add("world");
GenericCollectionProgram::isEven);
GenericCollectionProgram::isOdd);
GenericCollectionProgram::isPrime);
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.
import java.io.*;
import java.util.*;
int marks;
public Student(String studentId, String name, String rollNo, String studentClass, int marks, String address)
@Override public String toString() { return "Student_id: " + studentId + ", Name: " + name +
", Class: " + studentClass + ", Marks: " + marks + ", Address: " + address;
ObjectOutputStream(fos)) { oos.writeObject(student);
} catch (IOException e) {
// ii) Display Database (Read from file) public static void displayDatabase() {
if (!recordFound) {
File("tempDatabase.txt");
ObjectInputStream(fis);
while (true) {
try {
(!student.studentId.equals(studentId))
{ oos.writeObject(student);
} else
{ recordDeleted = true;
} catch (EOFException e)
if (recordDeleted) {
} else {
tempFile.renameTo(originalFile)) {
}
// iv) Update Record (Modify student details) public static void updateRecord(String
ObjectInputStream(fis);
while (true) {
try {
(!student.studentId.equals(studentId))
{ oos.writeObject(student);
} else {
} catch (EOFException e)
if (recordUpdated) {
} else {
tempFile.renameTo(originalFile)) {
}
// v) Search Record (Find student by ID or name) public static void
FileInputStream(FILE_NAME);
while (true) {
try {
if (student.studentId.equals(searchTerm) || student.name.equalsIgnoreCase(searchTerm)) {
} catch (EOFException e)
if (!recordFound) {
while (true) {
System.out.println("6. Exit");
System.out.print("Enter your choice: "); int
//Consume newline
switch (choice)
{ case 1:
createDatabase(student); break;
case 2:
displayDatabase(); break;
case 3:
break;
case 4:
newline
updateRecord(updateId, updatedStudent);
break;
case 5:
break;
case 6:
System.out.println("Exiting...");
scanner.close(); return;
default:
}}
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
information
import java.util.Scanner;
balance += amount;
amountWithdrawnToday += amount;
checkBalance() {
displayAccountInfo() {
// Method to reset the daily withdrawal limit (to be called at the end of the day) public void
args) {
initialBalance = scanner.nextDouble();
dailyLimit = scanner.nextDouble();
(running) {
System.out.println("6. Exit");
choice = scanner.nextInt();
switch (choice)
{ case 1:
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;
break;
default:
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.
{ assemble(); addAccessories();
finalMakeup();
}
class Hatchback extends Car { public void
assemble() {
assemble() {
}}
void assemble() {
System.out.println("Adding luxury SUV accessories (GPS, high-quality sound system, off-road tires)...");
}}
{ return null;
}
Hatchback();
Sedan();
SUV();
} return
null;
}}
(hatchback != null) {
(sedan != null) {
if (suv != null) {
} }}
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;
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!");
}
}
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;
// 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.");
}
}
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..
// 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);
import java.util.LinkedList;
// Constructor
public CustomLinkedList() {
list = new LinkedList<>();
}
// Adding elements
customList.addElement(10);
customList.addElement(20);
customList.addElement(30);
customList.displayList();
import java.util.ArrayList;
public class CustomArrayList {
private ArrayList<Integer> list;
// Constructor
public CustomArrayList() {
list = new ArrayList<>();
}
// Adding elements
customList.addElement(10);
customList.addElement(20);
customList.addElement(30);
customList.displayList();
// Base class
class Account {
protected String cust_name;
protected int acc_no;
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;
// Main class
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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);
}
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.");
}
import java.util.Scanner;
// OnlineCourse Interface - Defines a method to display course details
interface OnlineCourse {
void getDetails(); // Method to display course details
}
// 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.");
}
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).
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
}
}
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
@Override
public void swim() {
System.out.println("Duck is swimming in the water.");
}
}
@Override
public void swim() {
System.out.println("Frog is swimming in the pond.");
}
}
@Override
public void swim() {
System.out.println("Turtle is swimming in the water.");
}
}
@Override
public void swim() {
System.out.println("Penguin is swimming in the icy waters.");
}
}
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.
@Override
public int getSSCMarks() {
return 85; // Example SSC marks for Harish
}
@Override
public int getHSCMarks() {
return 90; // Example HSC marks for Harish
}
}
@Override
public int getHSCMarks() {
return 88; // Example HSC marks for Jayant
}
}
@Override
public int getSSCMarks() {
return 92; // Example SSC marks for Vijay
}
@Override
public int getHSCMarks() {
return 87; // Example HSC marks for Vijay
}
}
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;
// Cat class inherits from Animal class and adds skinColour attribute
class Cat extends Animal {
private String 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());
}
}
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.