The Effectively Final Requirement
You'll learn why lambda expressions can only access local variables that never change after initialization.
When a lambda expression captures a local variable from its surrounding scope, Java enforces a strict rule: that variable must be effectively final. This means the variable either has the final keyword or is never reassigned after its initial assignment.
Why This Rule Exists
Lambda expressions can be executed later or in different contexts (like in streams or callbacks). If the lambda could see a variable that keeps changing, the behavior would become unpredictable and confusing. Which value would it see—the original one, or the latest one?
Java solves this by requiring captured variables to be stable. The lambda captures the value at the time it's created, not a reference to a changing variable.
What "Effectively Final" Means
A variable is effectively final if you could add the final keyword without causing a compilation error. In other words, you assign it once and never change it:
int multiplier = 10; // effectively final
IntUnaryOperator triple = x -> x * multiplier; // OK - captures multiplier
// multiplier = 20; // If you uncomment this, compilation fails
When It Fails
If you reassign the variable anywhere in the scope, the lambda can no longer capture it:
int count = 5;
count = 10; // reassignment!
IntConsumer printer = x -> System.out.println(x + count); // ERROR
The compiler will tell you: "local variables referenced from a lambda expression must be final or effectively final."
Key Takeaway: Lambda expressions can only capture local variables that are effectively final—never reassigned after initialization—ensuring predictable, safe behavior when the lambda executes later.