Search code examples
javaeclipsevariablesdeclarationfinal

Declaring local variables as final without initializer and assigning in if-statement


I just made a small code change to silence a FindBugs warning which required moving some code to an anonymous inner class. In order to access some variables, I had to declare those as final. So this is the code snippet after the change:

final File[] libPath; // libPath is final but assignment takes place later
if (libraryPath != null) {
    libPath = pathToFiles(libraryPath);
} else {
    libPath = new File[0];
}

This compiles just fine with language set to Java 6 in current Eclipse (Version 3.7.1). However I'm quite sure this used to give an error in some previous version. Seems the compiler accepts this construct when it can determine that there will be.

My question is: is this legal in Java 6 or is it something that now works due to a side effect of Java 7 support being added to eclipse 3.7.1? We have seen such side effects with certain usage of generics that works in 3.7.1 but didn't compile in 3.7.0.


Solution

  • This was allowed and worked fine since Java 1.1 and will not get you in trouble with other compilers or IDEs.

    It is standard behaviour in Java and was first formally specified in the Java Language Specification 2nd Edition.