nerdexam
Oracle

1Z0-809 · Question #197

Given: class Resource implements AutoCloseable { public void close() throws Exception { System.out.print("Close-"); } public void open() { System.out.print("Open-"); } } and this code fragment…

The correct answer is C. A compilation error occurs at line n1. Option C is correct because the try-with-resources syntax requires a resource declaration (including the type), not a bare assignment to an already-declared variable. Writing try (resl = new Resource()) is syntactically illegal - the compiler expects either try (Resource resl =…

Question

Given: class Resource implements AutoCloseable { public void close() throws Exception { System.out.print("Close-"); } public void open() { System.out.print("Open-"); } } and this code fragment: Resource resl = new Resource(); try { resl.open(); resl.close(); } catch (Exception e) { System.out.println("Exception - 1"); } try (resl = new Resource()) { // line n1 resl.open(); } catch (Exception e) { System.out.println("Exception - 2"); } What is the result?

Options

  • AOpen-Close-Exception-1
  • BOpen-Close-Open-Close-
  • CA compilation error occurs at line n1.
  • DOpen-Close-Open-

How the community answered

(43 responses)
  • A
    2% (1)
  • B
    12% (5)
  • C
    79% (34)
  • D
    7% (3)

Explanation

Option C is correct because the try-with-resources syntax requires a resource declaration (including the type), not a bare assignment to an already-declared variable. Writing try (resl = new Resource()) is syntactically illegal - the compiler expects either try (Resource resl = new Resource()) or, in Java 9+, a reference to an effectively final variable like try (resl) where resl is not reassigned. Since the code fails at compile time, nothing runs.

Why the distractors are wrong:

  • A assumes the first try block throws an exception, but nothing in open() or the explicit close() call causes one here - and anyway the code never compiles.
  • B would be the correct output if line n1 used try (Resource r = new Resource()) - the first try prints Open-Close-, and the try-with-resources auto-close would add another Open-Close-.
  • D is wrong because try-with-resources always calls close() automatically, so skipping the close output is impossible even in a hypothetical passing scenario.

Memory tip: Think "declare to autoclose" - the try-with-resources parentheses must contain a full variable declaration (type included), not an assignment expression. If you see a bare variable = value without a type, flag it as a compile error.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice