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());- A. balance=50.0
- B. error: insufficient funds balance=100.0
- C. error: insufficient funds balance=50.0
- 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
- What is printed? java class Task { void execute() throws Exception { try { riskyStep(); } catch (RuntimeException e) { throw new…
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…
- What is printed? cpp struct Base { virtual std::string name() const { return "Base"; } }; struct Derived : Base { std::string name() const…
- What is printed? java class Resource { String name; Resource(String n) { name = n; } @Override protected void finalize() {…
- What is printed? cpp class Logger { public: static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int…
- What is printed? cpp struct Event { virtual void handle() const { cout << "generic-event "; } }; struct ClickEvent : Event { void handle()…