Resources declared in a try-with-resources header are closed automatically when the block ends, and they are closed in the reverse of the order they were opened, mirroring how nested resources should be released.
class Resource implements AutoCloseable {
final String name;
Resource(String name) {
this.name = name;
System.out.println("Opened " + name);
}
public void close() {
System.out.println("Closed " + name);
}
}
try (Resource first = new Resource("first"); Resource second = new Resource("second")) {
System.out.println("Using both resources");
}
Opened first
Opened second
Using both resources
Closed second
Closed first
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27