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
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)- A2% (1)
- B12% (5)
- C79% (34)
- D7% (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
tryblock throws an exception, but nothing inopen()or the explicitclose()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 printsOpen-Close-, and the try-with-resources auto-close would add anotherOpen-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.