How does it work?

Now, how does the compiler know which method to call when cleaning up resources? The answer is easy: Each class which can be used as a resource in the try-with-resources approach needs to implement the java.lang.AutoCloseable interface. This interface defines exactly one method, close(). So, the method name is always close() and the respective classes need to simply implement the AutoCloseable interface so that the compiler knows that the class can be used with the try-with-resources statement. In the background, the compiler automatically adds some additional code to properly handle the call to the close() method. Many classes in Java 7 already implement the AutoCloseable interface, among them various Printers and Writers, InputStreams and also as we saw above classes from the JDBC API. For a complete list of classes which support the AutoCloseable interface, refer to the Java 7 API Javadoc at https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html.

In the next section, we will have a closer look at another detail regarding this new feature: Suppressed exceptions.