Oops Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Oops Lab

Problem

Create a class "Room" which will hold the height, width and breadth of the room in three variables.

Create another class "Roomdemo" which will use the earlier class, create instances of rooms, set the

values of the variables and would calculate the volume of room.

Solution:

class Room {

// Instance variables to store the dimensions of the room

private double height;

private double width;

private double breadth;

// Constructor to initialize the dimensions of the room

public Room(double height, double width, double breadth) {

this.height = height;

this.width = width;

this.breadth = breadth;

// Method to calculate and return the volume of the room

public double calculateVolume() {

return height * width * breadth;

public class RoomDemo {

public static void main(String[] args) {

// Create instances of rooms and set their dimensions

Room room1 = new Room(3.0, 4.0, 5.0); // Example dimensions in meters

Room room2 = new Room(2.5, 3.5, 4.0); // Example dimensions in meters


// Calculate and display the volumes of the rooms

double volume1 = room1.calculateVolume();

double volume2 = room2.calculateVolume();

System.out.println("Volume of Room 1: " + volume1 + " cubic meters");

System.out.println("Volume of Room 2: " + volume2 + " cubic meters");

Problem:

Write a program to implement a class "student" with the following members.

i) Name of the student, ii) Marks of the student, iii )Function to assign initial values, iv)

Function to compute total average, v) Function to display the data

Write an appropriate main() to demonstrate the functioning of the above.

Solution:

class Student {

// Instance variables

private String name;

private double[] marks;

// Constructor to initialize the name and marks array

public Student(String name, int numSubjects) {

this.name = name;

this.marks = new double[numSubjects];

// Function to assign initial values to the marks array

public void setMarks(double[] marks) {

if (marks.length == this.marks.length) {

for (int i = 0; i < marks.length; i++) {


this.marks[i] = marks[i];

} else {

System.out.println("Number of subjects does not match the marks array length.");

// Function to compute the total and average marks

public double calculateTotal() {

double total = 0.0;

for (double mark : marks) {

total += mark;

return total;

public double calculateAverage() {

return calculateTotal() / marks.length;

// Function to display student data

public void displayData() {

System.out.println("Student Name: " + name);

System.out.println("Marks in each subject:");

for (int i = 0; i < marks.length; i++) {

System.out.println("Subject " + (i + 1) + ": " + marks[i]);

System.out.println("Total Marks: " + calculateTotal());

System.out.println("Average Marks: " + calculateAverage());

}
public class StudentDemo {

public static void main(String[] args) {

// Create a Student object

Student student1 = new Student("John", 5);

// Set the marks for the student

double[] marks = {85.5, 90.0, 78.5, 92.0, 88.5};

student1.setMarks(marks);

// Display student data

student1.displayData();

Problem:

Write a program to find given substring in a line of text taken as input and replace with another

substring.

Solution:

import java.util.Scanner;

public class SubstringReplacement {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input the line of text

System.out.print("Enter a line of text: ");

String inputText = scanner.nextLine();

// Input the substring to find

System.out.print("Enter the substring to find: ");


String findSubstring = scanner.nextLine();

// Input the substring to replace with

System.out.print("Enter the replacement substring: ");

String replaceSubstring = scanner.nextLine();

// Perform the replacement

String result = inputText.replace(findSubstring, replaceSubstring);

// Display the modified text

System.out.println("Modified text: " + result);

scanner.close();

Problem:

Write a program to implement a class "Salesman" with the attributes: name, salesman code,

sales amount and commission. The company calculates the commission of salesman

according to the following formula

8% if sales<2000

10% if sales<=2000 and >=5000

12% If sales>5000

Create 5 salesman objects and find their commissions for their sales.

Solution:

class Salesman {

private String name;

private int salesmanCode;

private double salesAmount;

private double commission;

public Salesman(String name, int salesmanCode, double salesAmount) {

this.name = name;

this.salesmanCode = salesmanCode;

this.salesAmount = salesAmount;}
public void calculateCommission() {

if (salesAmount < 2000) {

commission = salesAmount * 0.08; // 8% commission

} else if (salesAmount >= 2000 && salesAmount <= 5000) {

commission = salesAmount * 0.10; // 10% commission

} else {

commission = salesAmount * 0.12; // 12% commission

public void displaySalesmanInfo() {

System.out.println("Salesman Name: " + name);

System.out.println("Salesman Code: " + salesmanCode);

System.out.println("Sales Amount: $" + salesAmount);

System.out.println("Commission: $" + commission);

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

public class SalesmanDemo {

public static void main(String[] args) {

// Create 5 Salesman objects with their information

Salesman salesman1 = new Salesman("John", 101, 1500);

Salesman salesman2 = new Salesman("Alice", 102, 2200);

Salesman salesman3 = new Salesman("Bob", 103, 5500);

Salesman salesman4 = new Salesman("Eve", 104, 3500);

Salesman salesman5 = new Salesman("Mike", 105, 1800);

// Calculate commissions for each salesman

salesman1.calculateCommission();
salesman2.calculateCommission();

salesman3.calculateCommission();

salesman4.calculateCommission();

salesman5.calculateCommission();

// Display information for each salesman

salesman1.displaySalesmanInfo();

salesman2.displaySalesmanInfo();

salesman3.displaySalesmanInfo();

salesman4.displaySalesmanInfo();

salesman5.displaySalesmanInfo();

Problem:

An electric power distribution company charges its domestic consumers as follows:

Consumption Units Rate of charge


0-200 Rs. 0.50 per unit

201 -400 Rs.0.65 per unit excess of 200

401 - 600 Rs.0.80 per unit excess of 400

601 and above Rs.l .00 per unit excess of 600

Write a class "ElectricityBill", which will read the customer number and power consumed and billing

date and prints the amount to be paid by the customer and bill payment date (within 10 days from
the date of bill generation).

Solution:

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.Scanner;

class ElectricityBill {
private int customerNumber;

private double powerConsumed;

private Date billDate;

public ElectricityBill(int customerNumber, double powerConsumed) {

this.customerNumber = customerNumber;

this.powerConsumed = powerConsumed;

this.billDate = new Date(); // Initialize the bill date to the current date

public void calculateAmount() {

double amount = 0.0;

if (powerConsumed <= 200) {

amount = powerConsumed * 0.50;

} else if (powerConsumed <= 400) {

amount = 200 * 0.50 + (powerConsumed - 200) * 0.65;

} else if (powerConsumed <= 600) {

amount = 200 * 0.50 + 200 * 0.65 + (powerConsumed - 400) * 0.80;

} else {

amount = 200 * 0.50 + 200 * 0.65 + 200 * 0.80 + (powerConsumed - 600) * 1.00;

// Display the amount to be paid

System.out.println("Customer Number: " + customerNumber);

System.out.println("Bill Date: " + formatDate(billDate));

System.out.println("Amount to be paid: Rs. " + amount);

System.out.println("Payment Due Date: " + formatDate(calculateDueDate()));

// Helper method to format a date


private String formatDate(Date date) {

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

return dateFormat.format(date);

// Helper method to calculate the due date (10 days from the bill date)

private Date calculateDueDate() {

Calendar calendar = Calendar.getInstance();

calendar.setTime(billDate);

calendar.add(Calendar.DATE, 10);

return calendar.getTime();

public class ElectricityBillDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Customer Number: ");

int customerNumber = scanner.nextInt();

System.out.print("Enter Power Consumed (in units): ");

double powerConsumed = scanner.nextDouble();

ElectricityBill bill = new ElectricityBill(customerNumber, powerConsumed);

bill.calculateAmount();

scanner.close();

}
Problem:

Declare a class "BankAccount" with the following:

i.

Account Holder's Name

ii.

Account Number

Account Type (S for savings and C for Current)

Balance amount

Methods:

i.

Initialize data

ii.

Deposit money

Withdrawal of money — minimum deposit Rs. 1 ,000/-

iii.

To display all items

iv.

Write an appropriate main() to maintain details and access methods for N customers.

Solution:

import java.util.Scanner;

class BankAccount {

private String accountHolderName;

private long accountNumber;

private char accountType;

private double balance;

public void initializeData(String name, long accNumber, char accType, double initialBalance) {

accountHolderName = name;

accountNumber = accNumber;
accountType = accType;

balance = initialBalance;

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

System.out.println("Deposit successful. New balance: Rs. " + balance);

} else {

System.out.println("Invalid deposit amount.");

public void withdraw(double amount) {

if (amount >= 1000 && amount <= balance) {

balance -= amount;

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

} else {

System.out.println("Invalid withdrawal amount.");

public void displayAccountDetails() {

System.out.println("Account Holder's Name: " + accountHolderName);

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

System.out.println("Account Type: " + (accountType == 'S' ? "Savings" : "Current"));

System.out.println("Balance: Rs. " + balance);

public class BankAccountDemo {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int numCustomers = scanner.nextInt();

BankAccount[] accounts = new BankAccount[numCustomers];

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

accounts[i] = new BankAccount();

System.out.print("Enter Account Holder's Name: ");

String name = scanner.next();

System.out.print("Enter Account Number: ");

long accNumber = scanner.nextLong();

System.out.print("Enter Account Type (S for Savings, C for Current): ");

char accType = scanner.next().charAt(0);

System.out.print("Enter Initial Balance: ");

double initialBalance = scanner.nextDouble();

accounts[i].initializeData(name, accNumber, accType, initialBalance);

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

System.out.println("\nAccount Details for Customer " + (i + 1) + ":");

accounts[i].displayAccountDetails();

System.out.print("\nEnter deposit amount for Customer " + (i + 1) + ": ");


double depositAmount = scanner.nextDouble();

accounts[i].deposit(depositAmount);

System.out.print("Enter withdrawal amount for Customer " + (i + 1) + ": ");

double withdrawalAmount = scanner.nextDouble();

accounts[i].withdraw(withdrawalAmount);

System.out.println();

scanner.close();

}
9.Write a Java Class "Number" which will hold a decimal number. Create another class
"Octal", which
will extend the class number and with a method namely "ConvertOctal" it will convert the
decimal no.
into equivalent octal. Write appropriate main class to demonstrate the functioning of the
above.

// NumberConverter.java
class Number {

private double decimalNumber;

public Number(double decimalNumber) {

this.decimalNumber = decimalNumber;

public double getDecimalNumber() {

return decimalNumber;

class Octal extends Number {

public Octal(double decimalNumber) {

super(decimalNumber);

public String convertToOctal() {

long decimalPart = (long) getDecimalNumber();

double fractionalPart = getDecimalNumber() - decimalPart;

StringBuilder octalRepresentation = new StringBuilder();

octalRepresentation.append(Long.toOctalString(decimalPart));
if (fractionalPart > 0) {

octalRepresentation.append('.');

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

fractionalPart *= 8;

int octalDigit = (int) fractionalPart;

octalRepresentation.append(octalDigit);

fractionalPart -= octalDigit;

return octalRepresentation.toString();

public class NumberConverter {

public static void main(String[] args) {

double decimalNumber = 25.625;

Octal octalNumber = new Octal(decimalNumber);

String octalRepresentation = octalNumber.convertToOctal();

System.out.println("Decimal Number: " + decimalNumber);

System.out.println("Octal Representation: " + octalRepresentation);

}
10. Develop an abstract class "GeometricObject" which should have two abstract methods
findArea() and

findCircumference(). Write a subclass for "GeometricObject" called "Triangle" which wll be able to

calculate area and circumference for a triangle taking the sides form user as input.

import java.util.Scanner;

// Abstract class GeometricObject

abstract class GeometricObject {

// Abstract method to calculate the area

public abstract double findArea();

// Abstract method to calculate the circumference

public abstract double findCircumference();

// Subclass Triangle that extends GeometricObject

class Triangle extends GeometricObject {

private double sideA;

private double sideB;

private double sideC;

public Triangle(double sideA, double sideB, double sideC) {

this.sideA = sideA;

this.sideB = sideB;

this.sideC = sideC;

// @Override
public double findArea() {

double s = (sideA + sideB + sideC) / 2;

return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));

// @Override

public double findCircumference() {

return sideA + sideB + sideC;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of side A: ");

double sideA = scanner.nextDouble();

System.out.print("Enter the length of side B: ");

double sideB = scanner.nextDouble();

System.out.print("Enter the length of side C: ");

double sideC = scanner.nextDouble();

// Create a Triangle object

Triangle triangle = new Triangle(sideA, sideB, sideC);

// Calculate and display the area and circumference of the triangle

System.out.println("Area of the triangle: " + triangle.findArea());

System.out.println("Circumference of the triangle: " + triangle.findCircumference());

scanner.close();
}

Enter the length of side 1: 5

Enter the length of side 2: 7

Enter the length of side 3: 8

Area of the triangle: 17.320508075688775

Circumference of the triangle: 20.0

You might also like