Monday, July 28, 2014

Difference between final and effectively final in Java.

While reading about Local classes, observed a brand new word called effectively final. The statement I read goes like "However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final." So started to find the exact difference between them.


As language specification saying a final variable can be defined as An entity once that cannot be changed nor derived from later and an effectively final defined as variable or parameter whose value is never changed after it is initialized is effectively final. As you see there is no functional difference in definition as well other than that effectively word.


The only difference you can find is in the way the java compiler treats it. Even though the variable or field is not final and it is still not assigned anywhere else other than in initialization part, then compiler treats both as same. Consider the below final variable.

      final int fIntValue = 10;  
So we declared a final variable fintValue and if we try to change the value of this variable again (other than constructor) we'll run into a compilation error. Consider  another variable non final variable 
      int normaIntValue = 10;  
Though the variable normalIntValue declared as non final until unless you assign a new value to it , still compiler treats it as a final which is saying to be as effectively final. But the difference is that for a final variable if you want to assign a new value then compiler gives a error that it's a final , you can't do that. Where as if you try to assign a new value to a normal variable no errors or warnings but it is no more effectively final.

So the conclusion is that the effectively final variable is a variable which behave like a final variable without declaring it as final.


 Note: if a reference is not changed it is effectively final even if the object referenced is changed. 



Next >> Compiler version : String concatenation in java.

2 comments: