ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class R implements AutoCloseable {
    String n;
    R(String n, boolean fail) {
        if (fail) throw new IllegalStateException(n);
        this.n = n; System.out.print("open" + n + " ");
    }
    public void close() { System.out.print("close" + n + " "); }
}
// in main:
try (R a = new R("A", false); R b = new R("B", true)) {
    System.out.print("body ");
} catch (IllegalStateException e) { System.out.print("caught" + e.getMessage()); }
  1. A. openA caughtB
  2. B. openA closeA caughtB
  3. C. openA body closeA caughtB
  4. D. caughtB closeA

Correct answer: B. openA closeA caughtB

Resources are initialised in order; when creating b throws, the body is skipped but every resource ALREADY opened (a) is closed before the catch block runs.

More OOP with C++ and Java questions

Exams that ask this topic