There is a final keyword, which is used to make a reference value permanent. It means – the value can not be changed once defined.
Then there is effective final variable. These variables are not declared final. But, depending on the context they can be considered as final.
What do i mean from a context? you should ask that.
let us consider a pseudo code
- name = ‘anurag’
- lambda -> print(name)
- name = ‘anand’
The above code in java will work. Because, variable name does not change between it’s definition in line 1 and it’s use in line 2.
What does this mean? It means that , for code at line number 2 the value for name is final – it does not changes.
If we declare name as final at line 1, then it is not going to make any difference for code at line 2. Because, name is not changing anyway.
Now, I am going to write another pseudo-code
- name = ‘anurag’
- name = ‘anand’
- lambda -> print(name)
The above code in java, the programming language will not work. you will get a compile time error.
error: local variables referenced from a lambda expression must be final or effectively final
Because, anonymous function, inner class and lambda need a effective final object.
Earlier, it was mandatory to have the variable declared as final, but i think it happened after java 7 that we can use effective final values, too.
A simple code to generate a compile time error.
import java.util.function.IntUnaryOperator; public class EffectiveFinal { public static void main(String ... args) { int effectiveFinal = 23; effectiveFinal = 12; IntUnaryOperator mulByEffectiveFinal = (num) -> num * effectiveFinal; } }
If you comment out or move effectiveFinal = 12;
, then above code will compile without error. And, the effectiveFinal variable will really become effective variable.