Java 9 try-with-resources Improvement

Java 7 introduces a new approach for closing resources by try-with-resources statement. After that, Java 9 try-with-resources makes an improved way of writing code. Now we can simplify our code and keep it cleaner and clearer.

Related post: Java 7 – try-with-resources Statement

1. Java 7 try-with-resources

This is the way we use it from Java 7:

It is good, but we have to declare the variable in try() block.
That’s because we can’t use resource which is declared outside the try() block within it. If resource is already declared outside, we should re-refer it with local variable:

2. Java 9 try-with-resources improvement

Java 9 make things simple:

But we should notice that the br variable should be effectively final or declared final.

An effectively final variable is the variable that never changed after initializing. That means the compiler finds it never appear in assignments outside its initialization.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *