Try with resources is a special type of try statement where we can declare more than one resources within a single try statement. This feature came in Java 7. But it has some limitation with itself that overcomes in Java 9.
We will discuss this limitation through the examples. Now, Firstly we have to know what is resource actually, A resource is an object that must be closed after the program is finished with it. Now, we will come to what is try with resources?
The try with resources statement ensures that each one of the resources is closed at the end of the statement.
We will go through one example first how we close the resources before try with resources came into the picture.
So, the above example shows how we close the resources before try with resources feature. There was no automated way to close the resources we have to explicitly close the resources at last.
Now, we will go through one more example where we used try with resources that came in Java 7.
The above example has one limitation the Stream object we can only use within try block so the scope of that resource object that we declared with the try statement is local.
So, at last, we will go through with one more example to see how Java 9 overcome or solve this problem.
This example is self-explanatory itself. So, from the Java 9, we can pass the resource references that we can’t do till Java 8. And the scope problem is also resolved.
Note:- Any object that implements
java.lang.AutoCloseable, which includes all objects which implement,
java.io.Closeable can be used as a resource.
Happy Blogging 🙂