I want to use try-with-resources enhancement in Java 9 by putting reference variable inside try with resources instead of the entire variable declaration. I also know that to do that I must follow rule: Variable used as a try-with-resources resource should be final or effectively final
. First I will try with local and then with instance variable.
- Local variable:
-I make variable final, which follows the given rule and compiles fine:
public static void main (String[] args) throws IOException{
final FileWriter fw = new FileWriter ("test.txt");
try(fw) {
//some code
}
}
-If I also removed final keyword, it would again compile as fw
is considered effectively final -variables that are initialized only once and never mutated.
public static void main (String[] args) throws IOException{
FileWriter fw = new FileWriter ("test.txt");
try(fw) {
//some code
}
}
- Instance variable:
But will this same pattern work for instance variable as well? Let's try.
-First let's make instance variable final, which again follows the rule and compiles fine:
public class Test {
final FileWriter fw = new FileWriter ("a.txt");
void m1() throws IOException {
try(fw ) {
//some code
}
}
}
-If I remove final keyword, it should again compile, should it? As I am not mutating fw
anywhere but initializing it only once - should be effective final. Unfortunatelly, this won't work:
public class Test {
FileWriter fileWriter = new FileWriter ("a.txt");
void m1() throws IOException {
try(fileWriter) {
//some code
}
}
}
It gives me message: Variable used as a try-with-resources resource should be final or effectively final. So after all this, I am coming back to my first question. Can instance variable ever be effectively final or that term is used only for local variables? As I just showed, I am never mutating a variable (which should be considered effectively final), yet compiler never threats it as such.