Computer >> Computer tutorials >  >> Programming >> Java

What are the improvements for try-with-resources in Java 9?


Try-with-Resources has introduced in Java 7. The purpose of using it is to close the resources automatically after being used. The limitation is that resource needs to be declared before try or inside the try statement, if not it throws a compilation error.

Java 9 has improved try-with-resources and no longer needed to declare an object inside the try statement. 

In the below example, we have implemented a try-with-resources concept.

Example

import java.io.*;
public class TryWithResourceTest {
   public static void main(String[] args) throws FileNotFoundException {
      String line;
      Reader reader = new StringReader("tutorialspoint");
      BufferedReader breader = new BufferedReader(reader);
      try(breader) {
         while((line = breader.readLine()) != null) {
            System.out.println(line);
         }
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

Output

tutorialspoint