J.V · Java 25 practice question
What happens when a developer attempts to compile this Java 25 program?
public class Main {
static class Res implements AutoCloseable {
public void close() {}
}
public static void main(String[] args) {
Res r = new Res();
r = new Res();
try (r) {
System.out.println("used");
}
}
}
Check answer and explanation
Correct answer: It fails to compile because r is neither final nor effectively final
Explanation
An existing variable referenced in a try-with-resources resource specification must be final or effectively final and definitely assigned before the try statement; reassigning r violates effective finality and causes a compile-time error.
Common trap
Even though r is reassigned before the try statement begins, any reassignment prevents it from being effectively final. The compiler rejects the non-effectively-final resource variable rather than tracking multiple instances.
Source: JLS SE 25 §14.20.3. try -with-resources
Checked against the cited text on 2026-11-25.