Variants

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