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

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 21-Apr-2020 18:16:32
Advertisements