Advanced Java: Collections, Generics and More ยท More Language Features
Open a resource in the try header and Java closes it for you at the end, even if something goes wrong.
class Connection implements AutoCloseable {
String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
String query() {
return "data from " + name;
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public class TryWithResourcesDemo {
public static void main(String[] args) {
String result;
try (Connection db = new Connection("db")) {
result = db.query();
} // close() runs automatically here
System.out.println(result);
}
}Object) runs first.name in the Connection object changes from null to "db".open db.Connection() has finished, so its variables are gone.db is created on the stack and points to a new Connection on the heap: {name: "db"}.query() has finished, so its variables are gone.close db.close() has finished, so its variables are gone.db goes out of scope and disappears.data from db.