Search This Blog

Wednesday, November 14, 2018

Try-with-resources Example in JDK 9

In Java 7 and 8:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// try-with-resources statement of JDK 7 or 8
try (BufferedReader r1 = reader) {
// use buffered reader
} catch (IOException e) {
}
//The resource will be closed even without finally statement
which works just fine, but we still needed to declare a special variable in the try-with section. The cleaner and simpler way in JDK 9 is now:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// The JDK 9 way
try (reader) {
// use the reader
}catch (IOException e){
}
//The resource will be closed even without finally statement
This is more concise especially when you need the resource outside the scope of the try block.