OBJ Oriented Prog & Design 26th May 2024 Q&A


OBJ Oriented Prog & Design Q&A



Questions & Answers


( Suggestion :  keep refreshing the page for updated content & Search Questions Using Find )


Q1. Write a java program to print even odd numbers between  25 and 50 ( both inclusive) using separate threads  for printing  the even and odd numbers. 

Answer: 

public class EvenOddPrinter {

    public static void main(String[] args) {

        // Create two separate threads for printing even and odd numbers

        Thread evenThread = new Thread(new EvenPrinter());

        Thread oddThread = new Thread(new OddPrinter());


        // Start both threads

        evenThread.start();

        oddThread.start();

    }

}


class EvenPrinter implements Runnable {

    @Override

    public void run() {

        for (int i = 25; i <= 50; i++) {

            if (i % 2 == 0) {

                System.out.println("Even: " + i);

            }

        }

    }

}


class OddPrinter implements Runnable {

    @Override

    public void run() {

        for (int i = 25; i <= 50; i++) {

            if (i % 2 != 0) {

                System.out.println("Odd: " + i);

            }

        }

    }

}



Q2. Create a java class named Account class, which is representing a bank account where you can deposit and withdraw money. In this class create two methods withdraw and deposit. Initial Balance of Account is 3000 Rupees. Withdraw method parameter is amount and that amount we are subtracting from initial balance. If amount passes is greater than initial balance, it will throw Custom Exception InSufficient FundException, else it will calculate new balance by subtracting amount from initial balance. But what will happen if you want to withdraw money which exceed you bank balance? You will not be allowed, and this is where user defined exception comes into picture. Create a custom exception called InSufficient FundException to handle this scenario.

Answer: 


// Custom exception class for insufficient funds

class InSufficientFundException extends Exception {

    public InSufficientFundException(String message) {

        super(message);

    }

}


// Account class representing a bank account

public class Account {

    private double balance;


    // Constructor to initialize balance

    public Account() {

        this.balance = 3000; // Initial balance of 3000 Rupees

    }


    // Method to deposit money into the account

    public void deposit(double amount) {

        balance += amount;

        System.out.println("Deposited: " + amount + " Rupees");

    }


    // Method to withdraw money from the account

    public void withdraw(double amount) throws InSufficientFundException {

        if (amount > balance) {

            throw new InSufficientFundException("Insufficient funds. Cannot withdraw " + amount + " Rupees.");

        } else {

            balance -= amount;

            System.out.println("Withdrawn: " + amount + " Rupees");

        }

    }


    // Method to get the current balance

    public double getBalance() {

        return balance;

    }


    public static void main(String[] args) {

        Account account = new Account();

        System.out.println("Initial Balance: " + account.getBalance() + " Rupees");


        try {

            account.withdraw(4000); // Attempting to withdraw more than balance

        } catch (InSufficientFundException e) {

            System.out.println("Exception: " + e.getMessage());

        }


        try {

            account.deposit(2000); // Depositing money

            account.withdraw(1500); // Withdrawing valid amount

            System.out.println("Remaining Balance: " + account.getBalance() + " Rupees");

        } catch (InSufficientFundException e) {

            System.out.println("Exception: " + e.getMessage());

        }

    }

}


Q3. Understand the following  Java Program carefully and answer the given question properly.


i) Find out the erroneous statements in the given Java Program.

ii) Write down the reason why the statements are wrong.

iii) Fix the mistakess and tehn write a  right Java Program and write the ouputs.


class step11

{

final step1()

{

System.out.println("Everytime I am writing my answers on my own try and not copying from others");

}

}


abstract class step2 extends step1

{

abstract static void trying();

}


class step3 extends step2{

System.out.println("Every accomplishment starts with the decision to try . -John F Kennedy");

}

}


class FinalStep

{

public static void main(String args[]){

Step3 myself=new step3();


myself.trying();

System.out.println("The secret of making progress is to get started - Mark Twain ");

}

}


Answer: 


Erroneous Statements:

  1. final step1(): This line is attempting to declare a constructor with the final keyword, but constructors cannot be marked as final.
  2. abstract static void trying();: This line is attempting to declare an abstract static method in an abstract class. However, abstract methods cannot be static.
  3. System.out.println("Every accomplishment starts with the decision to try . -John F Kennedy");: This line is outside of any method or constructor, making it invalid. It should be placed inside a method or constructor.
  4. There's a missing opening brace { after the declaration of class step3.
Reasons for Errors:
  1. Constructors cannot be declared as final because they are implicitly final and cannot be overridden by subclasses.
  2. Abstract methods cannot be static because they need an instance of the class to be invoked, and static methods belong to the class itself.
  3. Print statements should be inside a method or a constructor. They cannot exist directly in a class.
  4. Every opening brace { should have a corresponding closing brace } to maintain syntactical correctness.
Corrected Java Program:

class Step1 {
    Step1() {
        System.out.println("Everytime I am writing my answers on my own try and not copying from others");
    }
}

abstract class Step2 extends Step1 {
    abstract void trying();
}

class Step3 extends Step2 {
    @Override
    void trying() {
        System.out.println("Every accomplishment starts with the decision to try. - John F Kennedy");
    }
}

class FinalStep {
    public static void main(String args[]) {
        Step3 myself = new Step3();
        myself.trying();
        System.out.println("The secret of making progress is to get started - Mark Twain");
    }
}

Output:

Everytime I am writing my answers on my own try and not copying from others
Every accomplishment starts with the decision to try. - John F Kennedy
Every accomplishment starts with the decision to try. - John F Kennedy
The secret of making progress is to get started - Mark Twain

Q4. Implement an interface called "TranportCompany" which contains a method getRegultedFarePerKm by accepting state name and another interface called "RegionalTranportOffice" whcich contains a method verifyRegistration and payRoadTax by accepting Vehicle Registration Number. Please write the code to cretate a class called Uber  that implements getRegulatedFarePerKm and payRoadTax and re-use the default implementation for verifyRegistration in "RegionalTranportOffice" interface. Class Uber shall print regulated fare and roadTaxPayment status.


Answer: 


// TransportCompany interface

interface TransportCompany {

    double getRegulatedFarePerKm(String state);

}


// RegionalTransportOffice interface

interface RegionalTransportOffice {

    default boolean verifyRegistration(String vehicleRegistrationNumber) {

        // Default implementation to verify registration

        // This is just a mock implementation; in a real-world scenario, this would query a database or an external service

        return vehicleRegistrationNumber != null && vehicleRegistrationNumber.matches("[A-Z]{2}[0-9]{2}[A-Z]{2}[0-9]{4}");

    }


    void payRoadTax(String vehicleRegistrationNumber);

}


// Uber class implementing both interfaces

public class Uber implements TransportCompany, RegionalTransportOffice {


    @Override

    public double getRegulatedFarePerKm(String state) {

        // A simple implementation where fare per km is determined by the state

        switch (state.toLowerCase()) {

            case "california":

                return 1.5;

            case "texas":

                return 1.2;

            case "florida":

                return 1.3;

            default:

                return 1.0; // Default fare

        }

    }


    @Override

    public void payRoadTax(String vehicleRegistrationNumber) {

        if (verifyRegistration(vehicleRegistrationNumber)) {

            System.out.println("Road tax paid for vehicle: " + vehicleRegistrationNumber);

        } else {

            System.out.println("Invalid vehicle registration number: " + vehicleRegistrationNumber);

        }

    }


    public static void main(String[] args) {

        Uber uber = new Uber();


        // Test getRegulatedFarePerKm

        String state = "California";

        double fare = uber.getRegulatedFarePerKm(state);

        System.out.println("Regulated fare per km in " + state + ": $" + fare);


        // Test payRoadTax

        String validRegistrationNumber = "CA12AB1234";

        String invalidRegistrationNumber = "12345";

        

        uber.payRoadTax(validRegistrationNumber);

        uber.payRoadTax(invalidRegistrationNumber);

    }

}


Q5. Write a Java program that illustrates the application of static and final keywords, and elucidates the concepts of mutable and immutable objects. Develop a class Student with the specified criteria below:  


i. Define the Student class with instance fields name and age.


ii. Incorporate a static field universityName, initialized to "XYZ University".


iii. Implement a constructor to initialize name and age.


iv. Create a method named displayInfo() to exhibit the student's name, age, and university name.


v. Ensure that the university Name remains unalterable after initialization, utilizing the final keyword.


vi. Showcase the disparity between mutable and immutable objects by instancing two Student objects: one with mutable properties and another with immutable properties.


Note to Students: Make sure your program follows the provided instructions carefully. Understand the significance of static and final keywords, and the basic differences between mutable and immutable objects. Your solution should be straightforward, to the point, and should clearly show your understanding of these Java concepts.


Your Java program should include:

  • Proper class structure with necessary instance fields and methods.
  • Correct implementation of constructors to initialize object properties.
  • Appropriate use of static and final keywords.
  • A method to display student information as specified.
  • Instances of Student objects demonstrating mutable and immutable properties.


Expected Output: Your program should produce output showcasing the information of both mutable and immutable Student objects, affirming the principles elucidated in the question.


Answer: 


public class Student {


    // Instance fields

    private String name;

    private int age;


    // Static field

    private static final String universityName = "XYZ University";


    // Constructor to initialize name and age

    public Student(String name, int age) {

        this.name = name;

        this.age = age;

    }


    // Method to display student information

    public void displayInfo() {

        System.out.println("Name: " + name + ", Age: " + age + ", University: " + universityName);

    }


    // Setter for name to demonstrate mutability

    public void setName(String name) {

        this.name = name;

    }


    // Getter for name

    public String getName() {

        return name;

    }


    // ImmutableStudent inner class to demonstrate immutability

    public static class ImmutableStudent {

        private final String name;

        private final int age;


        // Constructor to initialize name and age

        public ImmutableStudent(String name, int age) {

            this.name = name;

            this.age = age;

        }


        // Method to display immutable student information

        public void displayInfo() {

            System.out.println("Name: " + name + ", Age: " + age + ", University: " + universityName);

        }

    }


    public static void main(String[] args) {

        // Mutable Student object

        Student mutableStudent = new Student("Alice", 20);

        mutableStudent.displayInfo();

        

        // Changing name to demonstrate mutability

        mutableStudent.setName("Alicia");

        System.out.println("After changing name:");

        mutableStudent.displayInfo();


        // Immutable Student object

        ImmutableStudent immutableStudent = new ImmutableStudent("Bob", 22);

        immutableStudent.displayInfo();

        

        // Attempting to change the name of the immutable student would not work

        // immutableStudent.name = "Bobby"; // This line would cause a compilation error

    }

}


Q6. 

Answer: