Home > Java > javaTutorial > body text

Valid final variables in try-with-resources in Java 9?

PHPz
Release: 2023-09-20 08:25:02
forward
1386 people have browsed it

Java 9中的try-with-resources中的有效final变量?

Any variables used in the Try with Resource statement need to be declared in the Try statement until Java 8 version. Starting with Java 9, this restriction has been removed and any final or valid final variable is already blocked on the attempt. Effectively Final means that the variable cannot be changed once it is initialized.

Example

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class EffectivelyFinalTest {
   private static File file = new File("try_resources.txt");
      public static void main(String args[]) throws IOException {
      file.createNewFile();
      BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

      <strong>try</strong>(<strong>bufferedReader</strong>) {
         System.out.println("Can Use Final or Effectively Final in Try with Resources!");
      } finally {
         System.out.println("In finally block");
      }
}
}
Copy after login

Output

<strong>Can Use Final or Effectively Final in Try with Resources!
In finally block</strong>
Copy after login

The above is the detailed content of Valid final variables in try-with-resources 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
Popular Tutorials
More>
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!