Skip to content
Sharp

Exceptions · interview question

R prints "open X" in its constructor and "close X" in close(). Put the printed lines in order.

OrderingHard

R prints "open X" in its constructor and "close X" in close(). Put the printed lines in order.

try (R a = new R("A"); R b = new R("B")) {
    System.out.println("body");
}

Put the items in the correct order.

  1. open A
  2. close B
  3. close A
  4. body
  5. open B

Answer and explanation

Correct answer

1. open A
2. open B
3. body
4. close B
5. close A

Why

Resources are initialized in declaration order and closed in reverse order after the body, like nested try/finally blocks. That way a resource that depends on an earlier one is closed first.

Test yourself on Exceptions

A free test with instant, explained results. No account needed.

Start free test
All Exceptions questions →