ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Account {
    private double balance;
    Account(double b) { balance = b; }
    void withdraw(double amt) {
        if (amt > balance) throw new IllegalArgumentException("insufficient funds");
        balance -= amt;
    }
    double getBalance() { return balance; }
}
// in main:
Account acc = new Account(100);
try {
    acc.withdraw(50);
    acc.withdraw(100);
} catch (IllegalArgumentException e) {
    System.out.print("error: " + e.getMessage() + " ");
}
System.out.println("balance=" + acc.getBalance());
  1. A. balance=50.0
  2. B. error: insufficient funds balance=100.0
  3. C. error: insufficient funds balance=50.0
  4. D. error: insufficient funds balance=0.0

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

First withdraw(50) succeeds (100-50=50 remains). Second withdraw(100) exceeds the remaining balance of 50, throwing before any further mutation, caught by the catch block, which prints the error; getBalance() afterward still reflects only the first successful withdrawal: 50.0.

More OOP with C++ and Java questions

Exams that ask this topic