Java 9 - Try With Resources improvement


Try-with-resources was a good feature introduced in Java seven to mechanically manage resources victimisation Associate in using AutoCloseable interface. This helps a great deal, of course, as we've no have to be compelled to shut the resources expressly in our code.

Any object implementing java.lang.AutoCloseable or java.io.Closeable, interface can be used as a resource.Prior to Java nine, resources to be declared before attempt or within attempt statement we can say that we do not have to be compelled to shut resources (file, connection, network etc) expressly, try-with-resource shut that mechanically by victimization AutoClosable interface. Java 7, it allows us to declare resources to be used in a strive block with the reassurance that the resources are going to be closed after execution of that block.

Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example.

In this example, we'll use BufferedReader as resource to read a string and then BufferedReader is to 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();
      }
   }
}

Output

test

Here we need to declare a resource br1 within try statment and then use it.

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();
      }
   }
}

Output

test






javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition