J.V · Java 25 practice question

What is the result of compiling this Java 25 program?

public class Main {
  static class Res implements AutoCloseable {
    public void close() {}
  }
  public static void main(String[] args) {
    try (var r = new Res()) {
      r = null;
    }
  }
}
Choose one answer
Check answer and explanation

Correct answer: It fails to compile because a local variable declared in a resource specification is implicitly final

Explanation

A local variable declared in a try-with-resources resource specification is implicitly final if not explicitly declared final, so reassigning r to null causes a compile-time error.

Common trap

Reassigning a resource variable is disallowed at compile time precisely so the resource reference cannot be changed before closing. The code never reaches runtime because the compiler rejects the assignment to an implicitly final variable.

Source: JLS SE 25 §14.20.3. try -with-resources
Checked against the cited text on 2026-11-25.

Report an error in this question