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);
}
}- A. error: insufficient funds balance=50.0
- B. error: insufficient funds balance=-50.0
- C. balance=50.0
- 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
- What is printed? java public class Main { public static void main(String[] args) throws Exception { try { method1(); } catch…
- What is printed? java public class Main { static class Resource implements AutoCloseable { public void close() { System.out.print("closed…
- What happens when this is compiled? java class Base { void risky() throws java.io.IOException {} } class Sub extends Base { @Override void…
- What is printed? java public class Main { public static void main(String[] args) { Object o = "text"; try { Integer n = (Integer) o…
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…