0% found this document useful (0 votes)
7 views56 pages

Java

The document contains multiple Java programming examples, including basic programs like printing 'Hello World', calculating the sum of two numbers, and checking if a number is even or odd. It also includes more complex examples involving classes such as Person, Rectangle, Car, Book, BankAccount, and Employee, demonstrating object-oriented programming concepts. Additionally, it presents case studies for managing office spaces with classes for Position and Room, showcasing methods for area calculation and position manipulation.

Uploaded by

ajaypalprajapat7
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)
7 views56 pages

Java

The document contains multiple Java programming examples, including basic programs like printing 'Hello World', calculating the sum of two numbers, and checking if a number is even or odd. It also includes more complex examples involving classes such as Person, Rectangle, Car, Book, BankAccount, and Employee, demonstrating object-oriented programming concepts. Additionally, it presents case studies for managing office spaces with classes for Position and Room, showcasing methods for area calculation and position manipulation.

Uploaded by

ajaypalprajapat7
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/ 56

Q1. Write a program in Java to print “Hello World”?

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

Q2. Write a Java program to calculate the sum of two numbers. (Hint : import
java.util.Scanner)
import java.util.Scanner;

public class SumOfTwoNumbers {


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

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


int num1 = scanner.nextInt();

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


int num2 = scanner.nextInt();

int sum = num1 + num2;

System.out.println("The sum of the two numbers is: " + sum);

scanner.close();
}
}
Q3. Write a program to calculate area of a circle? The Uses should be prompted
to provide the radius.

import java.util.Scanner;
public class AreaOfCircle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the circle: ");


double radius = scanner.nextDouble();

double area = Math.PI * radius * radius;

System.out.println("The area of the circle is: " + area);

scanner.close();
}
}
Q4. Write a Java program to check if a number is even or odd.
import java.util.Scanner;

public class EvenOddChecker {


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

// Prompt user to enter a number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Check if the number is even or odd


if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
// Close the scanner
scanner.close();
}
}

Q5: Write a program for simple calculator?


import java.util.Scanner;

public class SimpleCalculator {


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

// Input two numbers


System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();

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


double num2 = scanner.nextDouble();

// Input operator
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);

double result;

switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid operator!");
}

scanner.close();
}
}
Q6: Write a function to reverse digits of an integer?
Algorithm: Reverse an Integer
Input: Read an integer number from the user.
Initialize:
reversedNumber to 0 (this will store the reversed number).
remainder to 0 (this will store the last digit of the current number).
While the number is not 0:
Extract the last digit of number and store it in remainder: remainder = number %
10
Update reversedNumber by appending remainder to its end: reversedNumber =
reversedNumber * 10 + remainder
Remove the last digit from number: number = number / 10

import java.util.Scanner;

public class ReverseInteger {

// Function to reverse digits of an integer


public static int reverseDigits(int number) {
int reversedNumber = 0;
int remainder;

while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number = number / 10;
}

return reversedNumber;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input from user


System.out.print("Enter an integer: ");
int num = scanner.nextInt();

// Call the reverse function


int reversed = reverseDigits(num);

// Output the result


System.out.println("Reversed number: " + reversed);
scanner.close();
}
}

Q TRY YOURSELF:
a. Creating a Simple Class:
o Objective: Create a class named Person with attributes like name and age.
Write
a method to display these attributes.
o Task: Instantiate objects of this class and print the details of each person.
b. Class with Methods:
o Objective: Create a class named Rectangle with attributes length and width.
Write methods to calculate the area and perimeter of the rectangle.
o Task: Create objects of Rectangle class, set their attributes, and print the area
and perimeter.
c. Constructor Usage:
o Objective: Create a class named Car with attributes model and year. Implement
a constructor to initialize these attributes.
o Task: Instantiate Car objects using the constructor and display the car details.

a)public class Person {


String name;
int age;

// Method to display person's details


void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


// Creating objects
Person person1 = new Person();
person1.name = "Alice";
person1.age = 25;

Person person2 = new Person();


person2.name = "Bob";
person2.age = 30;

// Display details
person1.display();
person2.display();
}
}

b)public class Rectangle {


double length;
double width;

// Method to calculate area


double calculateArea() {
return length * width;
}

// Method to calculate perimeter


double calculatePerimeter() {
return 2 * (length + width);
}

public static void main(String[] args) {


Rectangle rect1 = new Rectangle();
rect1.length = 10;
rect1.width = 5;
System.out.println("Area: " + rect1.calculateArea());
System.out.println("Perimeter: " + rect1.calculatePerimeter());
}
}
c)public class Car {
String model;
int year;

// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}

// Method to display car details


void displayDetails() {
System.out.println("Model: " + model + ", Year: " + year);
}

public static void main(String[] args) {


Car car1 = new Car("Toyota Camry", 2020);
Car car2 = new Car("Honda Civic", 2022);

car1.displayDetails();
car2.displayDetails();
}
}

Example 1: Library System


1. Class: Book
o Attributes: title, author, isbn, publishedYear
o Methods: borrowBook(), returnBook(), displayDetails()
2. Objects:
o Object 1: Book Harry Potter
 Attributes: title = "Harry Potter and the Philosopher's Stone",
author = "J.K. Rowling", isbn = "978-0747532699",
publishedYear = 1997
o Object 2: Book The Hobbit
 Attributes: title = "The Hobbit", author = "J.R.R. Tolkien",
isbn = "978-0261103344", publishedYear = 1937

public class Book {


String title, author, isbn;
int publishedYear;

// Constructor
Book(String title, String author, String isbn, int publishedYear) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.publishedYear = publishedYear;
}

void borrowBook() {
System.out.println("You have borrowed: " + title);
}

void returnBook() {
System.out.println("You have returned: " + title);
}

void displayDetails() {
System.out.println("Title: " + title + ", Author: " + author + ", ISBN: " + isbn
+ ", Year: " + publishedYear);
}

public static void main(String[] args) {


Book book1 = new Book("Harry Potter and the Philosopher's Stone", "J.K.
Rowling", "978-0747532699", 1997);
Book book2 = new Book("The Hobbit", "J.R.R. Tolkien", "978-0261103344",
1937);

book1.displayDetails();
book1.borrowBook();

book2.displayDetails();
book2.returnBook();
}
}

Example 2: Banking System


1. Class: BankAccount
o Attributes: accountNumber, accountHolderName, balance
o Methods: deposit(), withdraw(), displayBalance()2. Objects:
o Object 1: BankAccount Account1
 Attributes: accountNumber = "123456789", accountHolderName =
"Alice", balance = 5000.0
o Object 2: BankAccount Account2
 Attributes: accountNumber = "987654321", accountHolderName =
"Bob", balance = 3000.0

public class BankAccount {


String accountNumber, accountHolderName;
double balance;
// Constructor
BankAccount(String accountNumber, String accountHolderName, double
balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

void deposit(double amount) {


balance += amount;
System.out.println("Deposited " + amount + ". New Balance: " + balance);
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew " + amount + ". New Balance: " +
balance);
} else {
System.out.println("Insufficient balance!");
}
}

void displayBalance() {
System.out.println(accountHolderName + "'s Balance: " + balance);
}

public static void main(String[] args) {


BankAccount account1 = new BankAccount("123456789", "Alice", 5000.0);
BankAccount account2 = new BankAccount("987654321", "Bob", 3000.0);

account1.deposit(1000);
account1.withdraw(200);
account1.displayBalance();

account2.withdraw(3500);
account2.displayBalance();
}
}

Example 3: Employee Management System


1. Class: Employee
o Attributes: employeeID, name, position, salary
o Methods: work(), takeLeave(), displayDetails()
2. Objects:
o Object 1: Employee John
 Attributes: employeeID = 101, name = "John Doe", position =
"Software Engineer", salary = 60000.0
o Object 2: Employee Jane
 Attributes: employeeID = 102, name = "Jane Smith", position =
"Project Manager", salary = 80000.0

public class Employee {


int employeeID;
String name, position;
double salary;

// Constructor
Employee(int employeeID, String name, String position, double salary) {
this.employeeID = employeeID;
this.name = name;
this.position = position;
this.salary = salary;
}
void work() {
System.out.println(name + " is working as a " + position + ".");
}

void takeLeave(int days) {


System.out.println(name + " has taken " + days + " days of leave.");
}

void displayDetails() {
System.out.println("ID: " + employeeID + ", Name: " + name + ", Position: "
+ position + ", Salary: $" + salary);
}

public static void main(String[] args) {


Employee emp1 = new Employee(101, "John Doe", "Software Engineer",
60000.0);
Employee emp2 = new Employee(102, "Jane Smith", "Project Manager",
80000.0);

emp1.displayDetails();
emp1.work();
emp1.takeLeave(3);

emp2.displayDetails();
emp2.work();
}
}

Case Study: Office Space Management (Simple)


Imagine you are developing a software system to manage office spaces in a
corporate building.
The building has multiple rooms, each with a specific position, width, and height.
Your task is to
create a program that helps manage and manipulate these room objects.
Requirements:
1. Create a Position class:
o int x
o int y
Include a constructor that initializes x and y with the given values.
2. Create a Room class:
o Position position
o int width
o int height
Include two constructors:
o One that initializes the position with a Position object and sets the width and
height.
o Another that initializes the position to (0, 0) and sets the width and height
with given values.
Add the following methods to the Room class:
o int getArea(): Returns the area of the room.
o void move(int x, int y): Moves the position to a new location (x, y).
3. Main Program: In the main program of the OfficeManagement class, do the
following:
o Declare and create a Position object cornerOne with coordinates (15, 30).
o Declare and create two Room objects, roomOne with cornerOne, width 200,
and
height 300, and roomTwo with position (0, 0), width 100, and height 150.
o Display the width, height, and area of roomOne.
o Set the position of roomTwo to be the same as cornerOne and display the new
position.
o Move roomTwo to the position (50, 80) and display the updated coordinates.

Sample Output:
Width of roomOne: 200
Height of roomOne: 300
Area of roomOne: 60000
X Position of roomTwo: 15
Y Position of roomTwo: 30
X Position of roomTwo: 50
Y Position of roomTwo: 80

// Position class
class Position {
int x;
int y;

// Constructor to initialize x and y


Position(int x, int y) {
this.x = x;
this.y = y;
}
}

// Room class
class Room {
Position position;
int width;
int height;

// Constructor with a given Position object


Room(Position position, int width, int height) {
this.position = position;
this.width = width;
this.height = height;
}

// Constructor with default Position (0,0)


Room(int width, int height) {
this.position = new Position(0, 0);
this.width = width;
this.height = height;
}

// Method to get the area of the room


int getArea() {
return width * height;
}

// Method to move the room to a new position


void move(int x, int y) {
position.x = x;
position.y = y;
}
}

// Main class
public class OfficeManagement {
public static void main(String[] args) {
// Create Position object
Position cornerOne = new Position(15, 30);

// Create two Room objects


Room roomOne = new Room(cornerOne, 200, 300);
Room roomTwo = new Room(100, 150);

// Display width, height, and area of roomOne


System.out.println("Width of roomOne: " + roomOne.width);
System.out.println("Height of roomOne: " + roomOne.height);
System.out.println("Area of roomOne: " + roomOne.getArea());
// Set position of roomTwo to cornerOne
roomTwo.position = cornerOne;
System.out.println("X Position of roomTwo: " + roomTwo.position.x);
System.out.println("Y Position of roomTwo: " + roomTwo.position.y);

// Move roomTwo to new position (50, 80)


roomTwo.move(50, 80);
System.out.println("X Position of roomTwo: " + roomTwo.position.x);
System.out.println("Y Position of roomTwo: " + roomTwo.position.y);
}
}

Case Study: Office Space Management (Extended)


Imagine you are developing a software system to manage office spaces in a
corporate building.
The building has multiple rooms, each with a specific position, width, and height.
Your task is to
create a program that helps manage and manipulate these room objects.
Requirements:
1. Create a Position class:
o int x
o int y
Include a constructor that initializes x and y with the given values.
2. Create a Room class:
o Position position
o int width
o int height
Include two constructors:
o One that initializes the position with a Position object and sets the width and
height.
o Another that initializes the position to (0, 0) and sets the width and height
with given values.
Add the following methods to the Room class:
o int getArea(): Returns the area of the room.
o void move(int x, int y): Moves the position to a new location (x, y).
3. Main Program: In the main program of the OfficeManagement class, do the
following:
o Declare and create a Position object cornerOne with coordinates (15, 30).
o Declare and create two Room objects, roomOne with cornerOne, width 200,
and
height 300, and roomTwo with position (0, 0), width 100, and height 150.
Sample Output:
Width of roomOne: 200
Height of roomOne: 300
Area of roomOne: 60000
X Position of roomTwo: 15
Y Position of roomTwo: 30
X Position of roomTwo: 50
Y Position of roomTwo: 80
This case study demonstrates how you can apply object-oriented principles to
real-life scenarios,
such as managing office spaces in a corporate building. If you need any further
clarification or
have additional questions, feel free to ask!
make it more complex
Increase the complexity by adding inheritance
Got it! Let's enhance the case study by incorporating inheritance to model
different types of
rooms in the office building.
o Set the position of roomTwo to be the same as cornerOne and display the new
position.
o Move roomTwo to the position (50, 80) and display the updated
coordinatesSample Output:
Width of roomOne: 200
Height of roomOne: 300
Area of roomOne: 60000
X Position of roomTwo: 15
Y Position of roomTwo: 30
X Position of roomTwo: 50
Y Position of roomTwo: 80
This case study demonstrates how you can apply object-oriented principles to
real-life scenarios,
such as managing office spaces in a corporate building. If you need any further
clarification or
have additional questions, feel free to ask!
make it more complex
Increase the complexity by adding inheritance
Got it! Let's enhance the case study by incorporating inheritance to model
different types of
rooms in the office building.

// Position class
class Position {
int x, y;

Position(int x, int y) {
this.x = x;
this.y = y;
}
}

// Base Room class


class Room {
Position position;
int width, height;

Room(Position position, int width, int height) {


this.position = position;
this.width = width;
this.height = height;
}

Room(int width, int height) {


this.position = new Position(0, 0);
this.width = width;
this.height = height;
}

int getArea() {
return width * height;
}

void move(int x, int y) {


position.x = x;
position.y = y;
}

void displayDetails() {
System.out.println("Width: " + width);
System.out.println("Height: " + height);
System.out.println("Area: " + getArea());
System.out.println("Position -> X: " + position.x + ", Y: " + position.y);
}
}

// Derived class: ConferenceRoom


class ConferenceRoom extends Room {
int numberOfChairs;

ConferenceRoom(Position position, int width, int height, int numberOfChairs) {


super(position, width, height);
this.numberOfChairs = numberOfChairs;
}

void displayRoomType() {
System.out.println("Room Type: Conference Room");
System.out.println("Number of Chairs: " + numberOfChairs);
}
}

// Derived class: ExecutiveCabin


class ExecutiveCabin extends Room {
String occupantName;

ExecutiveCabin(Position position, int width, int height, String occupantName) {


super(position, width, height);
this.occupantName = occupantName;
}

void displayRoomType() {
System.out.println("Room Type: Executive Cabin");
System.out.println("Occupied by: " + occupantName);
}
}

// Main class
public class OfficeManagement {
public static void main(String[] args) {
// Create position object
Position cornerOne = new Position(15, 30);

// Create base Room object


Room roomOne = new Room(cornerOne, 200, 300);
System.out.println("--- Room One ---");
roomOne.displayDetails();

// Create ConferenceRoom object


ConferenceRoom roomTwo = new ConferenceRoom(new Position(0, 0), 100,
150, 20);

// Set position of roomTwo to cornerOne


roomTwo.position = cornerOne;
System.out.println("\n--- Room Two (Conference Room, after setting to
cornerOne) ---");
System.out.println("X Position of roomTwo: " + roomTwo.position.x);
System.out.println("Y Position of roomTwo: " + roomTwo.position.y);

// Move roomTwo to (50, 80)


roomTwo.move(50, 80);
System.out.println("X Position of roomTwo: " + roomTwo.position.x);
System.out.println("Y Position of roomTwo: " + roomTwo.position.y);
roomTwo.displayRoomType();

// Create ExecutiveCabin object


ExecutiveCabin execRoom = new ExecutiveCabin(new Position(10, 10), 120,
200, "Mr. Rahul Sharma");
System.out.println("\n--- Executive Cabin ---");
execRoom.displayDetails();
execRoom.displayRoomType();
}
}

Case Study: Managing Office Spaces in a Corporate Building (Complex)


Scenario:
TechCorp, a rapidly growing technology company, is expanding its office space in
a corporate
building. To efficiently manage the office spaces, the company needs a software
system to track
and manipulate the room configurations. Your task is to develop a program that
can handle
different types of rooms in the office building, such as regular office rooms and
conference
rooms. The goal is to create a flexible and maintainable system using object-
oriented principles.
Requirements:
1. Position Class:
o Attributes:
▪ int x: The x-coordinate of the room's position.
▪ int y: The y-coordinate of the room's position.
o Constructor:
▪ Initializes x and y with the given values.
2. Space Class (Base Class):
o Attributes:
▪ Position position: The position of the space.
▪ int width: The width of the space.
▪ int height: The height of the space.
o Constructor:
▪ Initializes the position with a Position object and sets the width and
height.
o Methods:
▪ int getArea(): Returns the area of the space.
▪ void move(int x, int y): Moves the position to a new location (x,
y).
3. Office Class (Derived from Space):
o Attributes:
▪ int numberOfDesks: The number of desks in the office.
o Constructor:
▪ Initializes the position, width, height, and numberOfDesks.
o Methods:
▪ void displayDetails(): Displays the details of the office, including the
number of desks.
4. ConferenceRoom Class (Derived from Space):
o Attributes:
▪ int seatingCapacity: The seating capacity of the conference room.
o Constructor:
▪ Initializes the position, width, height, and seatingCapacity.
o Methods:
▪ void displayDetails(): Displays the details of the conference room,
including the seating capacity.
Main Program: In the main program of the OfficeManagement class, do the
following:
o Declare and create a Position object cornerOne with coordinates (15, 30).
o Declare and create an Office object officeOne with cornerOne, width 200,
height 300, and numberOfDesks as 10.
o Declare and create a ConferenceRoom object conferenceRoomOne with
position
(0, 0), width 100, height 150, and seatingCapacity as 20.
o Display the width, height, and area of officeOne.
o Display the details of officeOne.
o Set the position of conferenceRoomOne to be the same as cornerOne and
display
the new position.
o Move conferenceRoomOne to the position (50, 80) and display the updated
coordinates.
o Display the details of conferenceRoomOne

class Position:
def __init__(self, x, y):
self.x = x
self.y = y

class Space:
def __init__(self, position, width, height):
self.position = position
self.width = width
self.height = height

def getArea(self):
return self.width * self.height

def move(self, x, y):


self.position.x = x
self.position.y = y

class Office(Space):
def __init__(self, position, width, height, numberOfDesks):
super().__init__(position, width, height)
self.numberOfDesks = numberOfDesks

def displayDetails(self):
print(f"Office Details: \nPosition: ({self.position.x}, {self.position.y})")
print(f"Width: {self.width}, Height: {self.height}, Number of Desks:
{self.numberOfDesks}")

class ConferenceRoom(Space):
def __init__(self, position, width, height, seatingCapacity):
super().__init__(position, width, height)
self.seatingCapacity = seatingCapacity

def displayDetails(self):
print(f"Conference Room Details: \nPosition: ({self.position.x},
{self.position.y})")
print(f"Width: {self.width}, Height: {self.height}, Seating Capacity:
{self.seatingCapacity}")

class OfficeManagement:
def __init__(self):
# Create Position object for cornerOne
cornerOne = Position(15, 30)

# Create Office object


officeOne = Office(cornerOne, 200, 300, 10)

# Create ConferenceRoom object


conferenceRoomOne = ConferenceRoom(Position(0, 0), 100, 150, 20)

# Display the width, height, and area of officeOne


print(f"Office One - Width: {officeOne.width}, Height: {officeOne.height},
Area: {officeOne.getArea()}")

# Display the details of officeOne


officeOne.displayDetails()

# Set the position of conferenceRoomOne to cornerOne and display the new


position
conferenceRoomOne.position = cornerOne
print(f"Conference Room One Position: ({conferenceRoomOne.position.x},
{conferenceRoomOne.position.y})")

# Move conferenceRoomOne to position (50, 80) and display the updated


coordinates
conferenceRoomOne.move(50, 80)
print(f"Updated Conference Room One Position:
({conferenceRoomOne.position.x}, {conferenceRoomOne.position.y})")

# Display the details of conferenceRoomOne


conferenceRoomOne.displayDetails()

# Run the OfficeManagement program


office_management = OfficeManagement()
1. Design a Student Management System
Topic: Classes, Objects, Inheritance, Collections
Task: Create a class hierarchy for a student management system.
● Base Class: Student
o Fields: name, rollNumber, dob, address
o Methods: Constructor, displayDetails(), calculateAge()
● Subclasses:
o UndergraduateStudent: Inherits from Student, adds a field yearOfStudy and a
method to display undergraduate-specific details.
o GraduateStudent: Inherits from Student, adds a field thesisTitle and a
method to display graduate-specific details.
● Additional Requirement:
o Create an interface Exam with methods registerForExam() and takeExam().
o Implement the Exam interface in both UndergraduateStudent and
GraduateStudent classes.
● System Requirements:
o Create a class StudentManagementSystem that manages a collection of
students
(using ArrayList<Student>). Provide functionality to add students, remove
students, and display all students in the system.

from datetime import datetime

class Student:
def __init__(self, name, rollNumber, dob, address):
self.name = name
self.rollNumber = rollNumber
self.dob = dob # dob should be a string in 'YYYY-MM-DD' format
self.address = address

def displayDetails(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.rollNumber}")
print(f"Date of Birth: {self.dob}")
print(f"Address: {self.address}")

def calculateAge(self):
today = datetime.today()
dob = datetime.strptime(self.dob, '%Y-%m-%d')
age = today.year - dob.year
if today.month < dob.month or (today.month == dob.month and today.day
< dob.day):
age -= 1
return age

class UndergraduateStudent(Student):
def __init__(self, name, rollNumber, dob, address, yearOfStudy):
super().__init__(name, rollNumber, dob, address)
self.yearOfStudy = yearOfStudy

def displayDetails(self):
super().displayDetails()
print(f"Year of Study: {self.yearOfStudy}")

def registerForExam(self):
print(f"{self.name} has been registered for the undergraduate exam.")

def takeExam(self):
print(f"{self.name} is taking the undergraduate exam.")

from abc import ABC, abstractmethod

class Exam(ABC):
@abstractmethod
def registerForExam(self):
pass

@abstractmethod
def takeExam(self):
pass
from typing import List

class StudentManagementSystem:
def __init__(self):
self.students: List[Student] = []

def addStudent(self, student: Student):


self.students.append(student)

def removeStudent(self, rollNumber: str):


self.students = [student for student in self.students if student.rollNumber !=
rollNumber]

def displayAllStudents(self):
if not self.students:
print("No students in the system.")
return
for student in self.students:
student.displayDetails()
print(f"Age: {student.calculateAge()} years\n")

# Create instances of Undergraduate and Graduate students


ug_student = UndergraduateStudent(name="John Doe", rollNumber="U123",
dob="2000-05-15", address="1234 Elm Street", yearOfStudy=2)
grad_student = GraduateStudent(name="Jane Smith", rollNumber="G456",
dob="1997-11-20", address="5678 Oak Avenue", thesisTitle="AI in Healthcare")

# Create the Student Management System


sms = StudentManagementSystem()

# Add students to the system


sms.addStudent(ug_student)
sms.addStudent(grad_student)

# Display all students


sms.displayAllStudents()

# Register students for exams and take exams


ug_student.registerForExam()
ug_student.takeExam()

grad_student.registerForExam()
grad_student.takeExam()

# Remove a student by roll number


sms.removeStudent("U123")
sms.displayAllStudents()

2. Implement a Library System with Book Borrowing and Returning


Topic: Classes, Objects, Inheritance, Interfaces, Collections
Task: Design a library system with books that can be borrowed and returned.
● Base Class: Book
o Fields: title, author, isbn, status (borrowed or available)
o Methods: Constructor, borrowBook(), returnBook(), displayBookDetails()
● Interface: Borrowable
o Methods: borrow(), return()
● Subclasses:
o PrintedBook: Inherits from Book, adds a field pageCount and overrides
borrowBook() and returnBook() to handle printed-specific logic.
o EBook: Inherits from Book, adds a field fileSize and overrides borrowBook()
and returnBook() to handle ebook-specific logic.
● Library System:
o Implement a class Library that contains a collection of Book objects
(ArrayList<Book>).
o Methods: addBook(Book book), borrowBook(String isbn),
returnBook(String isbn), and displayAllBooks().
o Ensure that a book can only be borrowed if it is available.

class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.status = "available" # Status can be 'available' or 'borrowed'

def borrowBook(self):
if self.status == "available":
self.status = "borrowed"
print(f"Book '{self.title}' has been borrowed.")
else:
print(f"Book '{self.title}' is already borrowed.")

def returnBook(self):
if self.status == "borrowed":
self.status = "available"
print(f"Book '{self.title}' has been returned.")
else:
print(f"Book '{self.title}' is already available.")

def displayBookDetails(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"ISBN: {self.isbn}")
print(f"Status: {self.status}")

from abc import ABC, abstractmethod

class Borrowable(ABC):
@abstractmethod
def borrow(self):
pass

@abstractmethod
def return(self):
pass

class PrintedBook(Book):
def __init__(self, title, author, isbn, pageCount):
super().__init__(title, author, isbn)
self.pageCount = pageCount

def borrowBook(self):
if self.status == "available":
self.status = "borrowed"
print(f"Printed Book '{self.title}' with {self.pageCount} pages has been
borrowed.")
else:
print(f"Printed Book '{self.title}' is already borrowed.")

def returnBook(self):
if self.status == "borrowed":
self.status = "available"
print(f"Printed Book '{self.title}' has been returned.")
else:
print(f"Printed Book '{self.title}' is already available.")

class EBook(Book):
def __init__(self, title, author, isbn, fileSize):
super().__init__(title, author, isbn)
self.fileSize = fileSize

def borrowBook(self):
if self.status == "available":
self.status = "borrowed"
print(f"EBook '{self.title}' with file size {self.fileSize}MB has been
borrowed.")
else:
print(f"EBook '{self.title}' is already borrowed.")

def returnBook(self):
if self.status == "borrowed":
self.status = "available"
print(f"EBook '{self.title}' has been returned.")
else:
print(f"EBook '{self.title}' is already available.")

from typing import List

class Library:
def __init__(self):
self.books: List[Book] = []

def addBook(self, book: Book):


self.books.append(book)

def borrowBook(self, isbn: str):


for book in self.books:
if book.isbn == isbn:
book.borrowBook()
return
print(f"Book with ISBN {isbn} not found.")

def returnBook(self, isbn: str):


for book in self.books:
if book.isbn == isbn:
book.returnBook()
return
print(f"Book with ISBN {isbn} not found.")

def displayAllBooks(self):
if not self.books:
print("No books in the library.")
return
for book in self.books:
book.displayBookDetails()
print("-------------------")

# Create some book instances


printed_book = PrintedBook(title="Harry Potter and the Philosopher's Stone",
author="J.K. Rowling", isbn="9780747532743", pageCount=223)
ebook = EBook(title="Digital Transformation", author="James Smith",
isbn="9781234567890", fileSize=5)

# Create a library instance


library = Library()

# Add books to the library


library.addBook(printed_book)
library.addBook(ebook)
# Display all books in the library
library.displayAllBooks()

# Borrow a book
library.borrowBook("9780747532743")

# Try to borrow the same book again


library.borrowBook("9780747532743")

# Return the book


library.returnBook("9780747532743")

# Display all books after returning


library.displayAllBooks()

# Borrow the ebook


library.borrowBook("9781234567890")

# Try to borrow the ebook again


library.borrowBook("9781234567890")

# Return the ebook


library.returnBook("9781234567890")

3. Design a Multi-level Inheritance Hierarchy for Vehicles


Topic: Inheritance, Interfaces, Polymorphism
Task: Implement a vehicle hierarchy that supports different types of vehicles,
their
characteristics, and actions.
● Interface: Vehicle
o Methods: start(), stop(), accelerate()
● Base Class: VehicleBase
o Fields: make, model, year
o Methods: Constructor, displayVehicleInfo()
● Subclasses:
o Car: Inherits from VehicleBase and implements Vehicle. Add a field fuelType
and override accelerate() to reflect car-specific acceleration behavior.
o Truck: Inherits from VehicleBase and implements Vehicle. Add a field
cargoCapacity and override accelerate() to reflect truck-specific acceleration
behavior.
o ElectricCar: Inherits from Car, implements Vehicle, and adds fields for
batteryCapacity and chargeLevel.
o ElectricTruck: Inherits from Truck, implements Vehicle, and adds fields for
batteryCapacity and chargeLevel.
● Additional Requirements:
o Implement a method refuel() in the Car class and charge() in the ElectricCar
class. Use polymorphism to call these methods depending on the vehicle type.

from abc import ABC, abstractmethod

class Vehicle(ABC):
@abstractmethod
def start(self):
pass

@abstractmethod
def stop(self):
pass

@abstractmethod
def accelerate(self):
pass
class VehicleBase:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def displayVehicleInfo(self):
print(f"Make: {self.make}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")

class Car(VehicleBase, Vehicle):


def __init__(self, make, model, year, fuelType):
super().__init__(make, model, year)
self.fuelType = fuelType

def start(self):
print(f"{self.make} {self.model} is starting.")

def stop(self):
print(f"{self.make} {self.model} is stopping.")

def accelerate(self):
print(f"{self.make} {self.model} is accelerating with {self.fuelType} fuel.")

def refuel(self):
print(f"Refueling the {self.make} {self.model} with {self.fuelType} fuel.")

class Truck(VehicleBase, Vehicle):


def __init__(self, make, model, year, cargoCapacity):
super().__init__(make, model, year)
self.cargoCapacity = cargoCapacity
def start(self):
print(f"{self.make} {self.model} truck is starting.")

def stop(self):
print(f"{self.make} {self.model} truck is stopping.")

def accelerate(self):
print(f"{self.make} {self.model} truck is accelerating with
{self.cargoCapacity} tons of cargo.")

class ElectricCar(Car):
def __init__(self, make, model, year, fuelType, batteryCapacity, chargeLevel):
super().__init__(make, model, year, fuelType)
self.batteryCapacity = batteryCapacity
self.chargeLevel = chargeLevel

def start(self):
print(f"{self.make} {self.model} electric car is starting silently.")

def stop(self):
print(f"{self.make} {self.model} electric car is stopping.")

def accelerate(self):
print(f"{self.make} {self.model} electric car is accelerating smoothly using
electric power.")

def charge(self):
print(f"Charging {self.make} {self.model} electric car. Current charge level:
{self.chargeLevel}%")

class ElectricTruck(Truck):
def __init__(self, make, model, year, cargoCapacity, batteryCapacity,
chargeLevel):
super().__init__(make, model, year, cargoCapacity)
self.batteryCapacity = batteryCapacity
self.chargeLevel = chargeLevel

def start(self):
print(f"{self.make} {self.model} electric truck is starting silently.")

def stop(self):
print(f"{self.make} {self.model} electric truck is stopping.")

def accelerate(self):
print(f"{self.make} {self.model} electric truck is accelerating smoothly with
{self.cargoCapacity} tons of cargo.")

def charge(self):
print(f"Charging {self.make} {self.model} electric truck. Current charge
level: {self.chargeLevel}%")

# Create vehicle objects


car = Car("Toyota", "Camry", 2020, "gasoline")
truck = Truck("Ford", "F-150", 2021, 3)
electric_car = ElectricCar("Tesla", "Model S", 2022, "electric", 100, 80)
electric_truck = ElectricTruck("Rivian", "R1T", 2023, 5, 200, 90)

# Create a list of vehicles


vehicles = [car, truck, electric_car, electric_truck]

# Start, accelerate, and stop each vehicle


for vehicle in vehicles:
vehicle.start()
vehicle.accelerate()
vehicle.stop()

# Demonstrate polymorphism for refuel and charge


for vehicle in vehicles:
if isinstance(vehicle, Car):
vehicle.refuel()
elif isinstance(vehicle, ElectricCar):
vehicle.charge()
if isinstance(vehicle, Truck):
vehicle.refuel()
elif isinstance(vehicle, ElectricTruck):
vehicle.charge()

# Create vehicle objects


car = Car("Toyota", "Camry", 2020, "gasoline")
truck = Truck("Ford", "F-150", 2021, 3)
electric_car = ElectricCar("Tesla", "Model S", 2022, "electric", 100, 80)
electric_truck = ElectricTruck("Rivian", "R1T", 2023, 5, 200, 90)

# Create a list of vehicles


vehicles = [car, truck, electric_car, electric_truck]

# Start, accelerate, and stop each vehicle


for vehicle in vehicles:
vehicle.start()
vehicle.accelerate()
vehicle.stop()

# Demonstrate polymorphism for refuel and charge


for vehicle in vehicles:
if isinstance(vehicle, Car):
vehicle.refuel()
elif isinstance(vehicle, ElectricCar):
vehicle.charge()
if isinstance(vehicle, Truck):
vehicle.refuel()
elif isinstance(vehicle, ElectricTruck):
vehicle.charge()

4. Design a Simple eCommerce System


Topic: Classes, Objects, Inheritance, Collections, Interfaces
Task: Build a simple eCommerce system for managing products and orders.
● Interface: Discountable
o Methods: applyDiscount()
● Base Class: Product
o Fields: productId, name, price
o Methods: Constructor, displayDetails()
● Subclasses:
o Electronics: Inherits from Product, adds a field for warrantyPeriod.
Implement the applyDiscount() method (electronics get a 10% discount).
o Clothing: Inherits from Product, adds a field for size. Implement the
applyDiscount() method (clothing gets a 20% discount).
o Food: Inherits from Product, adds a field for expiryDate. Implement the
applyDiscount() method (food gets a 5% discount).
● Order System:
o Create a class Order that contains a list of Product objects.
o Methods: addProduct(Product product), calculateTotalPrice(),
applyOrderDiscount(), and displayOrderDetails().
o Implement a method applyOrderDiscount() that applies the appropriate
discount to each product in the order.

from abc import ABC, abstractmethod


class Discountable(ABC):
@abstractmethod
def applyDiscount(self):
pass

class Product:
def __init__(self, productId, name, price):
self.productId = productId
self.name = name
self.price = price

def displayDetails(self):
print(f"Product ID: {self.productId}")
print(f"Name: {self.name}")
print(f"Price: ${self.price:.2f}")

class Electronics(Product, Discountable):


def __init__(self, productId, name, price, warrantyPeriod):
super().__init__(productId, name, price)
self.warrantyPeriod = warrantyPeriod

def applyDiscount(self):
self.price *= 0.9 # Apply 10% discount

def displayDetails(self):
super().displayDetails()
print(f"Warranty Period: {self.warrantyPeriod} months")

class Clothing(Product, Discountable):


def __init__(self, productId, name, price, size):
super().__init__(productId, name, price)
self.size = size
def applyDiscount(self):
self.price *= 0.8 # Apply 20% discount

def displayDetails(self):
super().displayDetails()
print(f"Size: {self.size}")

class Food(Product, Discountable):


def __init__(self, productId, name, price, expiryDate):
super().__init__(productId, name, price)
self.expiryDate = expiryDate

def applyDiscount(self):
self.price *= 0.95 # Apply 5% discount

def displayDetails(self):
super().displayDetails()
print(f"Expiry Date: {self.expiryDate}")

from typing import List

class Order:
def __init__(self):
self.products: List[Product] = []

def addProduct(self, product: Product):


self.products.append(product)

def applyOrderDiscount(self):
for product in self.products:
product.applyDiscount() # Apply the discount for each product
def calculateTotalPrice(self):
total = sum(product.price for product in self.products)
return total

def displayOrderDetails(self):
print("Order Details:")
for product in self.products:
product.displayDetails()
print("-------------------")
total_price = self.calculateTotalPrice()
print(f"Total Price: ${total_price:.2f}")

# Create product instances


laptop = Electronics(productId="E001", name="Laptop", price=1000,
warrantyPeriod=24)
shirt = Clothing(productId="C001", name="Shirt", price=50, size="M")
apple = Food(productId="F001", name="Apple", price=2, expiryDate="2025-12-
01")

# Create an order
order = Order()

# Add products to the order


order.addProduct(laptop)
order.addProduct(shirt)
order.addProduct(apple)

# Display order details before applying discounts


order.displayOrderDetails()

# Apply discounts to all products in the order


order.applyOrderDiscount()
# Display order details after applying discounts
print("\nAfter applying discounts:")
order.displayOrderDetails()

5. Design an Employee Payroll System Using Multiple Interfaces


Topic: Interfaces, Classes, Inheritance, Polymorphism
Task: Create a payroll system with employees and different payment methods.
● Interface: Payable
o Methods: calculateSalary()
● Base Class: Employee
o Fields: name, employeeId, hoursWorked, hourlyRate
o Methods: Constructor, displayDetails()
● Subclasses:
o HourlyEmployee: Inherits from Employee, implements Payable. The salary is
calculated as hoursWorked * hourlyRate.
o SalariedEmployee: Inherits from Employee, implements Payable. The salary is
fixed (e.g., $4000 per month).
● Additional Requirements:
o Create an interface BonusEligible with a method calculateBonus().
o Implement BonusEligible in the HourlyEmployee class to provide a 10% bonus
based on their salary.
o Create a PayrollSystem class that calculates and displays the total payroll for a
list of employees. Use polymorphism to calculate the salary for both types of
employees.

// Payable interface
interface Payable {
double calculateSalary();
}

// Employee base class


abstract class Employee {
String name;
String employeeId;
int hoursWorked;
double hourlyRate;

public Employee(String name, String employeeId, int hoursWorked, double


hourlyRate) {
this.name = name;
this.employeeId = employeeId;
this.hoursWorked = hoursWorked;
this.hourlyRate = hourlyRate;
}

public void displayDetails() {


System.out.println("Name: " + name);
System.out.println("Employee ID: " + employeeId);
System.out.println("Hours Worked: " + hoursWorked);
System.out.println("Hourly Rate: $" + hourlyRate);
}
}

// BonusEligible interface
interface BonusEligible {
double calculateBonus();
}

// HourlyEmployee class implementing Payable and BonusEligible


class HourlyEmployee extends Employee implements Payable, BonusEligible {

public HourlyEmployee(String name, String employeeId, int hoursWorked,


double hourlyRate) {
super(name, employeeId, hoursWorked, hourlyRate);
}

@Override
public double calculateSalary() {
return hoursWorked * hourlyRate;
}

@Override
public double calculateBonus() {
// 10% bonus of salary
return calculateSalary() * 0.10;
}

@Override
public void displayDetails() {
super.displayDetails();
double salary = calculateSalary();
double bonus = calculateBonus();
System.out.println("Salary: $" + salary);
System.out.println("Bonus: $" + bonus);
}
}

// SalariedEmployee class implementing Payable


class SalariedEmployee extends Employee implements Payable {

private double salary;

public SalariedEmployee(String name, String employeeId, double salary) {


super(name, employeeId, 0, 0); // No hours worked or hourly rate for
salaried employees
this.salary = salary;
}

@Override
public double calculateSalary() {
return salary;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Salary: $" + salary);
}
}
import java.util.ArrayList;
import java.util.List;

// PayrollSystem class
class PayrollSystem {
private List<Employee> employees = new ArrayList<>();

public void addEmployee(Employee employee) {


employees.add(employee);
}

public double calculateTotalPayroll() {


double totalPayroll = 0;
for (Employee employee : employees) {
totalPayroll += employee.calculateSalary();
if (employee instanceof BonusEligible) {
totalPayroll += ((BonusEligible) employee).calculateBonus();
}
}
return totalPayroll;
}

public void displayPayroll() {


System.out.println("Employee Payroll Details:");
for (Employee employee : employees) {
employee.displayDetails();
System.out.println("----------------------");
}
double totalPayroll = calculateTotalPayroll();
System.out.println("Total Payroll: $" + totalPayroll);
}
}

// Main class to test the payroll system


public class Main {
public static void main(String[] args) {
// Create instances of HourlyEmployee and SalariedEmployee
HourlyEmployee hourlyEmployee = new HourlyEmployee("Alice", "E001",
160, 20);
SalariedEmployee salariedEmployee = new SalariedEmployee("Bob",
"E002", 4000);

// Create the payroll system


PayrollSystem payrollSystem = new PayrollSystem();

// Add employees to the payroll system


payrollSystem.addEmployee(hourlyEmployee);
payrollSystem.addEmployee(salariedEmployee);

// Display the payroll details


payrollSystem.displayPayroll();
}
}
6. Design a Restaurant Ordering System with Strategy Pattern
Topic: Design Patterns (Strategy), Interfaces, Classes
Task: Implement a restaurant ordering system using the Strategy Pattern.
● Interface: PaymentMethod
o Methods: processPayment(double amount)
● Concrete Classes for Payment Methods:
o CreditCardPayment: Implements PaymentMethod and processes payment via
credit card.
o CashPayment: Implements PaymentMethod and processes payment via cash.
● Order Class:
o Fields: orderId, items (List of Item objects), totalAmount
o Methods: addItem(Item item), calculateTotal(),
setPaymentMethod(PaymentMethod paymentMethod), and processOrder().
● Item Class:
o Fields: name, price
o Methods: Constructor, displayItem()
● System Flow:
o The restaurant allows customers to add items to an order. Once the order is
complete, the user can select the payment method (credit card or cash). The
system then processes the payment and prints the receipt.

public interface PaymentMethod {


void processPayment(double amount);
}

public class CashPayment implements PaymentMethod {


@Override
public void processPayment(double amount) {
System.out.println("Processing cash payment of $" + amount);
}
}

public class Item {


private String name;
private double price;

public Item(String name, double price) {


this.name = name;
this.price = price;
}

public double getPrice() {


return price;
}

public void displayItem() {


System.out.println("Item: " + name + ", Price: $" + price);
}
}

import java.util.ArrayList;
import java.util.List;

public class Order {


private String orderId;
private List<Item> items;
private double totalAmount;
private PaymentMethod paymentMethod;

public Order(String orderId) {


this.orderId = orderId;
this.items = new ArrayList<>();
this.totalAmount = 0;
}

// Add item to the order


public void addItem(Item item) {
items.add(item);
}

// Calculate the total amount of the order


public void calculateTotal() {
totalAmount = 0;
for (Item item : items) {
totalAmount += item.getPrice();
}
}

// Set the payment method (strategy)


public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}

// Process the order (payment)


public void processOrder() {
System.out.println("Processing order " + orderId);
calculateTotal();
System.out.println("Total amount: $" + totalAmount);
if (paymentMethod != null) {
paymentMethod.processPayment(totalAmount);
} else {
System.out.println("No payment method selected.");
}
printReceipt();
}

// Print the receipt


private void printReceipt() {
System.out.println("\nReceipt:");
for (Item item : items) {
item.displayItem();
}
System.out.println("Total: $" + totalAmount);
System.out.println("Order ID: " + orderId);
}
}import java.util.ArrayList;
import java.util.List;

public class Order {


private String orderId;
private List<Item> items;
private double totalAmount;
private PaymentMethod paymentMethod;

public Order(String orderId) {


this.orderId = orderId;
this.items = new ArrayList<>();
this.totalAmount = 0;
}

// Add item to the order


public void addItem(Item item) {
items.add(item);
}

// Calculate the total amount of the order


public void calculateTotal() {
totalAmount = 0;
for (Item item : items) {
totalAmount += item.getPrice();
}
}

// Set the payment method (strategy)


public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}

// Process the order (payment)


public void processOrder() {
System.out.println("Processing order " + orderId);
calculateTotal();
System.out.println("Total amount: $" + totalAmount);
if (paymentMethod != null) {
paymentMethod.processPayment(totalAmount);
} else {
System.out.println("No payment method selected.");
}
printReceipt();
}

// Print the receipt


private void printReceipt() {
System.out.println("\nReceipt:");
for (Item item : items) {
item.displayItem();
}
System.out.println("Total: $" + totalAmount);
System.out.println("Order ID: " + orderId);
}
}

public class RestaurantSystem {


public static void main(String[] args) {
// Create items
Item pizza = new Item("Pizza", 12.99);
Item pasta = new Item("Pasta", 9.99);
Item soda = new Item("Soda", 1.99);

// Create an order
Order order = new Order("ORD123");

// Add items to the order


order.addItem(pizza);
order.addItem(pasta);
order.addItem(soda);

// Display order details before payment


order.processOrder();

// Now, let's change the payment method to CreditCardPayment


System.out.println("\nChanging payment method to Credit Card...");
order.setPaymentMethod(new CreditCardPayment());
order.processOrder();

// Alternatively, you can process payment via CashPayment


System.out.println("\nChanging payment method to Cash...");
order.setPaymentMethod(new CashPayment());
order.processOrder();
}
}

You might also like