ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class LowBalanceException extends Exception {
    LowBalanceException(String m) { super(m); }
}
class Account {
    double balance = 100;
    void withdraw(double amt) throws LowBalanceException {
        if (amt > balance) throw new LowBalanceException("insufficient funds");
        balance -= amt;
    }
}
public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        try {
            acc.withdraw(50);
            acc.withdraw(100);
        } catch (LowBalanceException e) {
            System.out.print("error: " + e.getMessage());
        }
        System.out.print(" balance=" + acc.balance);
    }
}
  1. A. error: insufficient funds balance=50.0
  2. B. error: insufficient funds balance=-50.0
  3. C. balance=50.0
  4. D. error: insufficient funds balance=0.0

Correct answer: A. error: insufficient funds balance=50.0

The first withdraw(50) succeeds, reducing balance to 50. The second withdraw(100) fails the check (100 > 50) and throws before balance is changed, so balance stays 50.0; the catch prints the error message, then execution continues to the final print, which reports the unchanged balance.

More OOP with C++ and Java questions

Exams that ask this topic