Last Updated: 06 March, 2023
Until Java 1.6, it is strongly advised to use the finally block to close resources explicitly that were opened as part of the try block.
The following problems arise from this approach:
To overcome these problems, Java introduced try-with-resources in its 1.7 version.
The try-with-resources statement automatically closes all the resources that were opened as a part of the try block once control reaches the end of the try block, either normally or abnormally.
Hence, we are not required to write a "finally block" to close the resource explicitly so that the length of the code will be reduced.
We can pass any object that implements java.lang.AutoCloseable interface, which includes all objects that implement java.io.Closeable interface.
Let's see the Syntax:
Example of try-with-resources in Java
Output
Name: Suresh, Roll: 21, Class: LKG
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com