Variants

Figure 514. Just finally, no catch Slide presentation
Scanner scanner = null;
try {
  scanner = new Scanner(System.in);
   ... // Something may fail
} finally {
  if (null != scanner) {
    scanner.close(); // Clean up, save resources!
  }
}

Figure 515. try-with-resources (Java 7) Slide presentation
try (final Scanner  scanner = new Scanner(System.in)) {
   ... // Something may fail
} // implicitly calling scanner.close()

Class must implement interface AutoCloseable.

Variable scanner's scope limited to block.

close() method will be called automatically before leaving block scope.


Figure 516. Scanner implementing AutoCloseable Slide presentation
public class Scanner
  implements AutoCloseable , ... {

  ...

  public void close() {...} 

}
Interface AutoCloseable {
  public void close(); // Signature, no
                       // implementation
}

Promise to implement all methods being declared in AutoCloseable.

Actually implementing a close() method.


Figure 517. No close() method in e.g. class String Slide presentation
try (final String s = new String()) { // Error: Required type: AutoCloseable; Provided: String
   ...
}