Variants

Figure 507. 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 508. 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 509. 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 510. No close() method in e.g. class String Slide presentation
try (final String s = new String()) { // Error: Required type: AutoCloseable; Provided: String
   ...
}