Try-with-resources Statement – Java 7

Many a times we forget to the close the file/jdbc resources that we open inside a try block after the operations are complete. This can cause memory leak issue.

Starting from JDK 1.7, a new feature try-with-resource was introduced.This feature allows user to declare one or more resources in the try block. The try-with-resources will close the resource at the end of the try block.

Syntax for try-with-resources :

Prior to JDK 1.7 we used to close the resources in the finally block

Using the try-with-resources in JDk 1.7

Please Note:

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces

 

Use of try-with-resources in JDBC statements