Java
Java
Q2. Write a Java program to calculate the sum of two numbers. (Hint : import
java.util.Scanner)
import java.util.Scanner;
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);
scanner.close();
}
}
Q4. Write a Java program to check if a number is even or odd.
import java.util.Scanner;
// 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;
while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number = number / 10;
}
return reversedNumber;
}
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.
// Display details
person1.display();
person2.display();
}
}
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
car1.displayDetails();
car2.displayDetails();
}
}
// 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);
}
book1.displayDetails();
book1.borrowBook();
book2.displayDetails();
book2.returnBook();
}
}
void displayBalance() {
System.out.println(accountHolderName + "'s Balance: " + balance);
}
account1.deposit(1000);
account1.withdraw(200);
account1.displayBalance();
account2.withdraw(3500);
account2.displayBalance();
}
}
// 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 displayDetails() {
System.out.println("ID: " + employeeID + ", Name: " + name + ", Position: "
+ position + ", Salary: $" + salary);
}
emp1.displayDetails();
emp1.work();
emp1.takeLeave(3);
emp2.displayDetails();
emp2.work();
}
}
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;
// Room class
class Room {
Position position;
int width;
int height;
// Main class
public class OfficeManagement {
public static void main(String[] args) {
// Create Position object
Position cornerOne = new Position(15, 30);
// Position class
class Position {
int x, y;
Position(int x, int y) {
this.x = x;
this.y = y;
}
}
int getArea() {
return width * height;
}
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);
}
}
void displayRoomType() {
System.out.println("Room Type: Conference Room");
System.out.println("Number of Chairs: " + numberOfChairs);
}
}
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);
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
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)
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.")
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 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")
grad_student.registerForExam()
grad_student.takeExam()
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}")
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.")
class Library:
def __init__(self):
self.books: List[Book] = []
def displayAllBooks(self):
if not self.books:
print("No books in the library.")
return
for book in self.books:
book.displayBookDetails()
print("-------------------")
# Borrow a book
library.borrowBook("9780747532743")
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}")
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.")
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}%")
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}")
def applyDiscount(self):
self.price *= 0.9 # Apply 10% discount
def displayDetails(self):
super().displayDetails()
print(f"Warranty Period: {self.warrantyPeriod} months")
def displayDetails(self):
super().displayDetails()
print(f"Size: {self.size}")
def applyDiscount(self):
self.price *= 0.95 # Apply 5% discount
def displayDetails(self):
super().displayDetails()
print(f"Expiry Date: {self.expiryDate}")
class Order:
def __init__(self):
self.products: List[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 an order
order = Order()
// Payable interface
interface Payable {
double calculateSalary();
}
// BonusEligible interface
interface BonusEligible {
double calculateBonus();
}
@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);
}
}
@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<>();
import java.util.ArrayList;
import java.util.List;
// Create an order
Order order = new Order("ORD123");