In Java 6, we open a file in a try block and close the file in the finally block
1. You'd have to check if your resource is null before closing it.
2. The closing itself can throw exceptions so finally had to contain another try – catch.
3. Programmers tend to forget to close their resources.
In JDK 7, a new “try-with-resources” approach is introduced.
When a try block is an end, it will close or release your opened file automatically.
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Benefits of using try with resources
1. Automatic resource management.
2. More readable code and the number of lines of code is reduced.
3. No need to have finally block just to close the resources.
4. We can open multiple resources in try-with-resources statement separated by a semicolon.
5. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.
Note for Point#5
We can extend the resource program to prove that.