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