Home> Java> javaTutorial> body text

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

王林
Release: 2023-08-25 22:57:02
forward
1208 people have browsed it

在Java 9中如何在try-with-resources语句中声明多个资源?

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

We can declaremultiple resourcesin the try block. The try initialization block can have any number of resources, which can be null or non-null.

In the following example, we can 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(); } } }
Copy after login

Output

test
Copy after login

The above is the detailed content of How to declare multiple resources in try-with-resources statement in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!