ProgrammingVery hardProduct-company MCQ pattern

What is printed?

What is printed?
class R implements AutoCloseable {
    String n;
    R(String n) { this.n = n; System.out.print("o" + n + " "); }
    public void close() { System.out.print("c" + n + " "); }
}
// in main:
try (R a = new R("A"); R b = new R("B")) {
    System.out.print("body ");
    throw new RuntimeException();
} catch (RuntimeException e) {
    System.out.print("catch ");
} finally {
    System.out.print("fin");
}
  1. A. oA oB body catch cB cA fin
  2. B. oA oB body catch fin cB cA
  3. C. oA oB body cB cA catch fin
  4. D. oA oB body cA cB catch fin

Correct answer: C. oA oB body cB cA catch fin

Resources open in order and close in reverse order (B then A), and they are closed before the catch block runs. finally runs last.

More OOP with C++ and Java questions

Exams that ask this topic