Guvi Task2 - Introduction to OOPs in Java

Solution - 1:

1) Create a class person with properties (name and age) with the following features:
a. Default age of the person should be 18;
b. A person object can be initialized with name and age;
c. Method to display name and age of the person.

(Note: For all solutions output will be executed at Test class)

public class Person {

    private String name;
    private int age;

    // Default constructor (sets default age to 18)
    public Person() {
        this.name = "Unknown";
        this.age = 18;
    }

    // Parameterized constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to set name and age
    public void setPersonDetails(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display name and age
    public void displayPersonDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
import java.util.Scanner;

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

        // Create a Person object using default constructor
        Person person1 = new Person();
        System.out.println("Default Person Details:");
        person1.displayPersonDetails();

        // Create another Person object using user input
        System.out.println("\nEnter details for a new person:");
        System.out.print("Enter Name: ");
        String name = scanner.nextLine();
        System.out.print("Enter Age: ");
        int age = scanner.nextInt();

        Person person2 = new Person(name, age);

        // Display details of the second person
        System.out.println("\nNew Person Details:");
        person2.displayPersonDetails();

    }
}

OUTPUT:

Default Person Details:

Name: Unknown

Age: 18

Enter details for a new person:

Enter Name: john

Enter Age: 25

New Person Details:

Name: john

Age: 25

Solution - 2:

2) Create class Product (pid, price, quantity) with a parameterized constructor.
Create a main function in a different class (say xyz) and perform the following tasks:

a. Accept five product information from the user and store in an array.
b. Find pid of the product with the highest price.
c. Create a method (with an array of product objects as an argument) in the xyz class to calculate and return the total amount spent on all products.
(Amount spent on a single product = price of product * quantity of product).

public class Product {
    // Properties
    private int pid;
    private double price;
    private int quantity;

    // Parameterized constructor
    public Product(int pid, double price, int quantity) {
        this.pid = pid;
        this.price = price;
        this.quantity = quantity;
    }

    // Getters
    public int getPid() {
        return pid;
    }

    public double getPrice() {
        return price;
    }

    public int getQuantity() {
        return quantity;
    }

    // Calculate the total cost of this product
    public double calculateTotal() {
        return price * quantity;
    }
}
import java.util.Scanner;

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

        // Array to store 5 Product objects
        Product[] products = new Product[5];

        // Accept product information from the user
        System.out.println("Enter details of 5 products (pid, price, quantity):");
        for (int i = 0; i < 5; i++) {
            System.out.print("Product " + (i + 1) + " - PID: ");
            int pid = scanner.nextInt();

            System.out.print("Price: ");
            double price = scanner.nextDouble();

            System.out.print("Quantity: ");
            int quantity = scanner.nextInt();

            // Create a Product object and store it in the array
            products[i] = new Product(pid, price, quantity);
        }

        // Find the PID of the product with the highest price
        int highestPricePid = findHighestPricePid(products);
        System.out.println("\nThe PID of the product with the highest price is: " + highestPricePid);

        // Calculate the total amount spent on all products
        double totalAmountSpent = calculateTotalAmountSpent(products);
        System.out.println("Total amount spent on all products: " + totalAmountSpent);
    }

    // Method to find the PID of the product with the highest price
    public static int findHighestPricePid(Product[] products) {
        int highestPid = -1;
        double highestPrice = 0;

        for (Product product : products) {
            if (product.getPrice() > highestPrice) {
                highestPrice = product.getPrice();
                highestPid = product.getPid();
            }
        }

        return highestPid;
    }

    // Method to calculate the total amount spent on all products
    public static double calculateTotalAmountSpent(Product[] products) {
        double totalAmount = 0;

        for (Product product : products) {
            totalAmount += product.calculateTotal();
        }

        return totalAmount;
    }
}

OUTPUT:

Enter details of 5 products (pid, price, quantity):

//(Note: the values given to PID, price and quantity are input from user)

Product 1 - PID: 101

Price: 50

Quantity: 2

Product 2 - PID: 102

Price: 100

Quantity: 1

Product 3 - PID: 103

Price: 40

Quantity: 3

Product 4 - PID: 104

Price: 120

Quantity: 1

Product 5 - PID: 105

Price: 60

Quantity: 2

The PID of the product with the highest price is: 104

Total amount spent on all products: 560.0

Solution - 3:

3) Create a class Account with a data member Balance. Create two constructors (no argument, and two arguments) and perform the following tasks:
a. Method to deposit the amount to the account.
b. Method to withdraw the amount from the account.
c. Method to display the Balance.

import java.util.Scanner;

public class Account {
    // Data member
    private double balance;

    // No-argument constructor (default balance is 0)
    public Account() {
        this.balance = 0;
    }

    // Constructor with initial balance
    public Account(double balance) {
        this.balance = balance;
    }

    // Method to deposit an amount
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Deposit amount must be positive.");
        }
    }

    // Method to withdraw an amount
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else if (amount > balance) {
            System.out.println("Insufficient balance!");
        } else {
            System.out.println("Withdrawal amount must be positive.");
        }
    }

    // Method to display the balance
    public void displayBalance() {
        System.out.println("Current Balance: " + balance);
    }
}
import java.util.Scanner;

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

        // Ask user to choose constructor
        System.out.println("Choose an option to create an account:");
        System.out.println("1. No initial balance");
        System.out.println("2. Initial balance");
        int choice = scanner.nextInt();

        Account account;

        if (choice == 1) {
            account = new Account(); // No-argument constructor
        } else if (choice == 2) {
            System.out.print("Enter initial balance: ");
            double initialBalance = scanner.nextDouble();
            account = new Account(initialBalance); // Parameterized constructor
        } else {
            System.out.println("Invalid choice! Creating default account.");
            account = new Account();
        }

        // Menu-driven program for deposit, withdrawal, and display
        while (true) {
            System.out.println("\nChoose an operation:");
            System.out.println("1. Deposit");
            System.out.println("2. Withdraw");
            System.out.println("3. Display Balance");
            System.out.println("4. Exit");

            int operation = scanner.nextInt();

            switch (operation) {
                case 1:
                    System.out.print("Enter amount to deposit: ");
                    double depositAmount = scanner.nextDouble();
                    account.deposit(depositAmount);
                    break;

                case 2:
                    System.out.print("Enter amount to withdraw: ");
                    double withdrawAmount = scanner.nextDouble();
                    account.withdraw(withdrawAmount);
                    break;

                case 3:
                    account.displayBalance();
                    break;

                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    scanner.close();
                    return;

                default:
                    System.out.println("Invalid choice! Please try again.");
            }
        }
    }
}

OUTPUT:

Choose an option to create an account:

  1. No initial balance

  2. Initial balance

    1

Choose an operation:

  1. Deposit

  2. Withdraw

  3. Display Balance

  4. Exit

    1

    Enter amount to deposit: 1000

    Deposited: 1000.0

Choose an operation:

  1. Deposit

  2. Withdraw

  3. Display Balance

  4. Exit

    2

    Enter amount to withdraw: 500

    Withdrawn: 500.0

Choose an operation:

  1. Deposit

  2. Withdraw

  3. Display Balance

  4. Exit

    3

    Current Balance: 500.0

Choose an operation:

  1. Deposit

  2. Withdraw

  3. Display Balance

  4. Exit

    4

    Exiting program. Goodbye!

Solution - 4:

4) Define a base class Person with attributes name and age.
Create a subclass employee that inherits from person and adds attributes like employeeID and salary.
Use the super keyword to initialize the Person attributes in the Employee constructor.

public class Person {
    // Attributes
    protected String name;
    protected int age;

    // Constructor for Person
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display person details
    public void displayPersonInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
public class Employee extends Person {
    // Additional attributes for Employee
    private int employeeID;
    private double salary;

    // Constructor for Employee (using super to initialize Person attributes)
    public Employee(String name, int age, int employeeID, double salary) {
        super(name, age); // Call to the superclass constructor
        this.employeeID = employeeID;
        this.salary = salary;
    }

    // Method to display employee details
    public void displayEmployeeInfo() {
        super.displayPersonInfo(); // Call the method from the Person class
        System.out.println("Employee ID: " + employeeID);
        System.out.println("Salary: " + salary);
    }
}
import java.util.Scanner;

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

        // Accept Person and Employee details
        System.out.print("Enter Name: ");
        String name = scanner.nextLine();
        System.out.print("Enter Age: ");
        int age = scanner.nextInt();
        System.out.print("Enter Employee ID: ");
        int employeeID = scanner.nextInt();
        System.out.print("Enter Salary: ");
        double salary = scanner.nextDouble();

        // Create Employee object
        Employee employee = new Employee(name, age, employeeID, salary);

        // Display Employee details
        System.out.println("\nEmployee Details:");
        employee.displayEmployeeInfo();

        scanner.close();
    }
}

OUTPUT:

Enter Name: Aravind

Enter Age: 23

Enter Employee ID: 11204

Enter Salary: 45000

Employee Details:

Name: Aravind

Age: 23

Employee ID: 11204

Salary: 45000.0