Any variable that has been used within Try with Resource statements requires to be declared within the Try statement up to Java 8 version. Since Java 9, this restriction has been removed, and any final or effectively final variables have been used inside the Try block. Effectively final means that the variable can't be changed once it has been 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)); try(bufferedReader) { System.out.println("Can Use Final or Effectively Final in Try with Resources!"); } finally { System.out.println("In finally block"); } } }
Output
Can Use Final or Effectively Final in Try with Resources! In finally block