A local variable from an enclosing scope used inside a lambda expression must be `final` or 'effectively final'. Why does Java enforce this rule?

Java interview question for Advanced practice.

Answer

The lambda expression effectively captures the value of the local variable, not the variable itself. Allowing modification would lead to inconsistent views of the variable's state.

Explanation

The correct answer is D. A lambda expression can be executed long after the method in which it was created has returned, meaning the local variable's stack frame is gone. To handle this, Java 'captures' the value of the local variable at the time of the lambda's creation. If the variable were allowed to be modified after being captured, there would be two different versions of it: the one inside the lambda and the one outside. To avoid this ambiguity and ensure consistent state, Java enforces that the variable cannot be changed after it is captured, which is what 'final' or 'effectively final' means.

Related Questions