Home  >  Article  >  Java  >  Valid final variables in try-with-resources in Java 9?

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

PHPz
PHPzforward
2023-09-20 08:25:021367browse

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

Output

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete