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, where only local variables that are final or effectively final can be used. If you try to modify such a variable after it has been used in a lambda, the compiler will produce an error.
Example:
int x = 10; // effectively final if not modified
Runnable r = () -> System.out.println(x);
r.run();
// If you add the line x = 20; after declaring the lambda, it will result in a compilation error
Thus, "effectively final" allows writing more concise code without explicitly specifying final, while maintaining safety and predictable behavior.