Quick revision
The short answer
The first snippet does not compile because a lambda may only use local variables that are final or effectively final, never changed after they are assigned, and count++ changes count. The fix is to count with a stream, list.stream().filter(Item::isActive).count(), to use a plain for loop, or, if a lambda is truly required, to use a holder such as AtomicInteger. The second snippet also does not compile: i is declared in the for statement, so its scope ends with the loop and println(i) refers to a name that no longer exists.
What to remember
In this answer, we saw that a lambda copies the values of the local variables it uses, so Java allows it to capture only final or effectively final locals; count++ breaks that rule. The cleanest fix is a stream count, then a plain loop, then an AtomicInteger, with an int[] holder as an unsafe last resort. The second snippet fails because a variable declared in a for statement goes out of scope when the loop ends. Fields can be changed inside lambdas because they are reached through this or the class, which is allowed but can cause data races.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The first snippet does not compile because a lambda may only use local variables that are final or effectively final, never changed after they are assigned, and count++ changes count. The fix is to count with a stream, list.stream().filter(Item::isActive).count(), to use a plain for loop, or, if a lambda is truly required, to use a holder such as AtomicInteger. The second snippet also does not compile: i is declared in the for statement, so its scope ends with the loop and println(i) refers to a name that no longer exists.
Why this question is asked
These two snippets look like beginner mistakes, but the rules behind them explain how lambdas really work and why Java chose to be strict. People coming from JavaScript or C# are often surprised that Java refuses to let a lambda change a local counter. Interviewers ask this to check that we can give the reason, not just the fix, and that we know the difference between capturing a local variable and using a field, which matters for thread safety. In this answer, we will recap scope and capture, reproduce both errors, explain why the capture rule exists, look at the fixes and what each one costs, and see why fields behave differently.
1A Quick Recap of Scope and Capture
The scope of a variable is the region of code where its name can be used. A local variable's scope runs from its declaration to the end of the block that contains it, the nearest pair of braces. A variable declared in the header of a for statement belongs to that statement, so its scope is the loop's condition, update and body, and nothing after it.
A lambda is a short anonymous function. When its body uses a local variable from the method around it, we say it captures that variable. Java allows capture only of variables that are final or effectively final. Effectively final means the variable is assigned exactly once and never changed, even if we did not write the final keyword.
2Reproducing Both Errors
Here are the snippets with the exact compiler messages from javac.
In the first case, count is changed inside the lambda, so it is not effectively final, and the compiler rejects the capture. Notice that the rule is about the whole method: even if we changed count only after the lambda, outside it, the capture would still be rejected, because count would no longer be assigned exactly once.
In the second case, i only exists inside the for statement. When the loop ends, the name is gone, so println(i) refers to nothing. If we want the final value of a loop counter, we declare it before the loop: int i; for (i = 0; i < 3; i++) { } System.out.println(i); prints 3.
3Why Java Only Captures Effectively Final Locals
The reason lies in where local variables live. A local variable belongs to one call of the method and lives in that call's stack frame, which disappears when the method returns. A lambda, however, can outlive the call: it can be stored in a field, returned, or handed to another thread. So Java does not give the lambda a reference to the variable itself. It copies the variable's value into the lambda object when the lambda is created.
If the variable could change afterwards, the copy and the original would silently disagree, and the lambda would show a stale value. Requiring effectively final variables makes the copy indistinguishable from the original. There is a second benefit: local variables are never shared between threads, because each thread has its own stack. If lambdas could write captured locals, code like list.parallelStream().forEach(x -> count++) would create data races on what looks like a private variable. The rule rules that out at compile time.
6 messages in order. Play them, or step through them one at a time.
The lambda carries a copy, so the original variable must never change.
4The Fixes and What Each Costs
The best fix depends on what the code is for. If the goal is just to count, the stream API already has the operation, and there is no mutable state at all.
The stream version states the intent and returns a long, because a stream count can exceed the int range. The plain loop is the simplest when the loop body does more than count. The AtomicInteger works because the variable counter itself never changes; it always points to the same object, and we change the object's contents. The same trick explains the int[] holder, but notice the difference: the array is not thread-safe, so if the lambda ever runs in a parallel stream, increments can be lost. That is why the holder is a last resort, and AtomicInteger is the safer one of the two.
5Why Fields Can Be Changed Inside Lambdas
A lambda can freely change an instance field or a static field. That is not an exception to the rule, because fields are not captured by value. An instance field is reached through this, the current object, which the lambda captures as a reference, and a static field is reached through the class. Both live on the heap and outlive any method call.
But there is a catch: precisely because fields are shared, changing them from lambdas brings back the problem the local variable rule prevents. If addActive is called from two threads, or the list is a parallel stream, total++ is a data race, and the final count can be wrong without any error. So the compiler allowing it does not make it safe.
6Follow-up questions
What does shadowing mean, and when does Java forbid it?
Shadowing is declaring a name that hides another variable with the same name in an outer scope. Java allows a local variable or parameter to shadow a field, which is why constructors can write this.name = name. It forbids a local variable from shadowing another local variable or parameter of the same method, including inside nested blocks and inside lambdas: int x = 1; Runnable r = () -> { int x = 2; }; fails with variable x is already defined. Lambda parameters cannot reuse an enclosing local name either. An anonymous inner class body, by contrast, starts a new scope and may shadow it, which is one of the small differences between the two.
Can a lambda read a variable that changes later, if it only reads it?
No. The rule is about the variable being assigned once anywhere in the method, not about what the lambda does with it. If we need a changing value, we copy it into a new effectively final variable just before creating the lambda, for example final int snapshot = count.
Do anonymous inner classes have the same capture rule?
Yes. Since Java 8 they also capture effectively final locals, and before Java 8 the variable had to be declared final explicitly. Lambdas simply follow the same rule.
7Conclusion
In this answer, we saw that a lambda copies the values of the local variables it uses, so Java allows it to capture only final or effectively final locals; count++ breaks that rule. The cleanest fix is a stream count, then a plain loop, then an AtomicInteger, with an int[] holder as an unsafe last resort. The second snippet fails because a variable declared in a for statement goes out of scope when the loop ends. Fields can be changed inside lambdas because they are reached through this or the class, which is allowed but can cause data races.
Open with
The first one does not compile because a lambda can only capture local variables that are final or effectively final, meaning assigned once and never changed, and count++ changes count.
Then, if they want more
The reason is that a local variable lives in the method's stack frame, while the lambda might run later or on another thread, so Java copies the value into the lambda when it is created.
If the variable could still change, the copy would be stale, and it would also let lambdas create data races on locals, which are otherwise never shared between threads. To fix it, I would use a stream: list.stream().filter(Item::isActive).count(), which has no mutable state at all.
If the loop does more work, a plain for loop is fine because there is no lambda. If I really need a lambda, an AtomicInteger works because the variable never changes, only the object it points to; an int array holder also compiles but is not thread-safe.
The second snippet also fails to compile: i is declared in the for statement, so its scope ends with the loop, and println(i) gives cannot find symbol. If I need the value after the loop, I declare i before it.
One related point: lambdas can change fields, because they reach them through this or the class rather than capturing a copy, but that brings back thread-safety problems, so the compiler accepting it does not make it safe.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Why does this not compile, and how do you fix it?": https://scrivio-interview-library.netlify.app/java/types-and-values/3a2b33b30e/