Senior
What is effectively final in Java and where is it used?
sobes.tech AI
Answer from AI
In Java, the term "effectively final" refers to local variables that are not declared with the final keyword but whose value does not change after initialization. That is, the variable behaves as final, even though it is not explicitly marked with this modifier.
This is important, for example, when using lambda expressions and anonymous classes: they can only capture local variables that are either final or effectively final. If a variable is modified after initialization, the compiler will produce an error.
Example:
int x = 10; // effectively final if not changed
Runnable r = () -> System.out.println(x);
// If later you write x = 20;, it will cause a compilation error
Thus, "effectively final" allows writing more concise code without explicitly specifying final, while maintaining safety and predictable behavior.