How to declare multiple resources in a try-with-resources statement in Java 9?


Try-with-resources statement has been improved in Java 9. If we already have a resource that is final or equivalent to the final variable, then we can use that variable in a try-with-resources statement without having to declare a new variable in a try-with-resources statement.

We can declare multiple resources in a try block. Try initialization block can have any number of resources resulting in either null or non-null resources.

In the below example, we can able to declare multiple resources in the try-with-resources statement.

Example

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

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

Output

test

Updated on: 21-Apr-2020

943 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements