logo

Try With Resources Improvement


Show

The try with resources improvement is a try statement with having one or more resources duly proclaimed. Here, the resource is an object which should be shut once it is no longer needed. The try-with-resources statement ensures that each and every resource is shut after the requirements are completed. Any object executing java.lang.AutoCloseable or java.io.Closeable, and the interface can be used as a resource.

Earlier to java 9, resources were to be proclaimed before try or inside try statements as given in the example that is given below. We will use BufferedReader as a resource to study a string in this example and then BufferedReader must be closed.

Tester.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;


public class Tester {
   public static void main(String[] args) throws IOException {
      System.out.println(readData("test"));
   } 
   static String readData(String message) throws IOException {
      Reader inputString = new StringReader(message);
      BufferedReader br = new BufferedReader(inputString);
      try (BufferedReader br1 = br) {
         return br1.readLine();
      }
   }
}

Result

test

Here, we have to announce a resource br1 within the try statement and then make use of it. But In Java 9, we don’t require to announce br1 anymore and also the given program gives the same result as given before.

Tester.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class Tester {
   public static void main(String[] args) throws IOException {
      System.out.println(readData("test"));
   } 
   static String readData(String message) throws IOException {
      Reader inputString = new StringReader(message);
      BufferedReader br = new BufferedReader(inputString);
      try (br) {
         return br.readLine();
      }
   }
}

Result

test