Quick revision
The short answer
The code does not compile: total is a local variable that the lambda changes, so it is not effectively final, and javac reports that local variables referenced from a lambda expression must be final or effectively final. The idiomatic rewrite is int total = orders.stream().mapToInt(Order::amount).sum(); and a plain for loop is equally fine here. Making total an instance field would compile, but that is shared mutable state and is not thread-safe.
What to remember
In this answer, we saw that the code fails to compile because the lambda assigns to total, so total is not effectively final, and lambdas can only capture effectively final locals. The clean rewrite is int total = orders.stream().mapToInt(Order::amount).sum(), which mutates nothing and stays correct in parallel; a plain for loop is equally fine. For BigDecimal amounts we reduce with BigDecimal::add, and for large totals we use mapToLong. Moving total to an instance field compiles, but it reintroduces shared mutable state that loses updates under parallel execution and leaks between calls.
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 code does not compile: total is a local variable that the lambda changes, so it is not effectively final, and javac reports that local variables referenced from a lambda expression must be final or effectively final. The idiomatic rewrite is int total = orders.stream().mapToInt(Order::amount).sum(); and a plain for loop is equally fine here. Making total an instance field would compile, but that is shared mutable state and is not thread-safe.
Why this question is asked
This two-line snippet is probably the most common first encounter with the effectively final rule. It looks completely reasonable, it is how we would write it in many other languages, and the compiler still refuses it. Interviewers ask it because the answer shows whether we understand why the rule exists and whether we reach for a clean rewrite or for a hack. In this answer, we will see the error and the reason behind it, write the stream version and the loop version, look at variations such as BigDecimal amounts and overflow, and explain why moving total to a field is the wrong fix.
1What the Compiler Says
Let us compile the code exactly as written.
A local variable is effectively final when nothing assigns to it after its initialisation. Here the lambda itself assigns to total with +=, so total is not effectively final, and a lambda may only use locals that are. The reason is that a lambda captures a copy of each local's value when it is created; it does not hold on to the variable. Locals live in the method's stack frame, which can be gone by the time a lambda runs, and a lambda may run on another thread. If changes were allowed, the copy and the variable would disagree, or several threads would update the same variable without any synchronisation. Java avoids both problems by forbidding the change.
Notice that forEach here would actually run on the calling thread, one order at a time. The compiler does not know that and does not try to; the rule applies to every lambda, because the same lambda could just as well be handed to a parallel stream or an executor.
2Rewrite 1: Let the Stream Do the Summing
The idiomatic fix is to stop mutating a variable from inside the lambda and let the stream produce the result. mapToInt turns each order into its int amount, giving an IntStream, and sum() adds them up.
Notice that no lambda changes anything. Order::amount is a method reference that only reads a value, and the stream combines the values. The variable total is assigned exactly once, so it is final in spirit, and the code says what it computes. mapToInt also avoids boxing every amount into an Integer, which map(Order::amount) followed by reduce would do.
This version is also safe to parallelise. If someone later writes orders.parallelStream(), each thread sums its own part and the partial sums are added at the end, with the same result, 200.
3Rewrite 2: A Plain for Loop
A loop is a perfectly good answer here, and many reviewers prefer it for something this simple. There is no lambda, so there is no capture rule; total is an ordinary local variable that the loop body updates.
The interview point is not that streams are always better. The point is that we should not fight the language by forcing a mutating loop body into a lambda. Either we express the computation as a reduction, or we write the loop.
4Variations Worth Knowing
Real code is rarely an int. Money is usually a BigDecimal, which has no primitive stream, so we reduce with BigDecimal::add starting from zero. Large totals can overflow an int silently, so for counts or cents that may grow we use mapToLong. And if we need several numbers at once, summaryStatistics gives the count, sum, minimum, maximum and average in one pass.
| Approach | Compiles? | Safe in parallel? | Verdict |
|---|---|---|---|
| Lambda changes a local | no | - | the original code |
mapToInt(Order::amount).sum() | yes | yes | idiomatic |
| for loop with a local | yes | not parallel | fine and clear |
int[] holder or AtomicInteger | yes | array no, atomic yes but slow | avoid |
| Lambda changes an instance field | yes | no | avoid |
5Why an Instance Field Is the Wrong Fix
Sometimes people move total to a field to get past the error, and it does compile. A lambda that uses a field captures this, the reference to the current object, and the field lives on the heap with the object, so the lambda can change it.
The compiler is satisfied, but the original danger is back. total += amount is a read, an add and a write. With a parallel stream, two threads read the same old total and both write their own result, so increments are lost and the answer changes from run to run. Even with a sequential stream, the field now carries state between calls: calling compute twice on the same Report doubles the total unless someone remembers to reset it. A field is the right home for state that belongs to the object, not for a temporary sum.
6Follow-up questions
Would an AtomicInteger fix the field version?
It would make the count correct, because addAndGet is atomic, but every thread would update the same memory location, so a parallel run can be slower than a simple loop, and the reset-between-calls problem remains. A reduction is both correct and faster.
Is forEach with a side effect ever acceptable?
Yes, when the side effect is the point, such as sending each order to a queue or printing it. forEach is for actions, not for computing a result. If the purpose is a value, use a reduction or a collector.
Why does mapToInt matter compared with map?
map(Order::amount) produces a Stream<Integer>, boxing every amount into an Integer object, and Stream has no sum method. mapToInt produces an IntStream of primitives with sum, average and summaryStatistics, and no boxing.
7Conclusion
In this answer, we saw that the code fails to compile because the lambda assigns to total, so total is not effectively final, and lambdas can only capture effectively final locals. The clean rewrite is int total = orders.stream().mapToInt(Order::amount).sum(), which mutates nothing and stays correct in parallel; a plain for loop is equally fine. For BigDecimal amounts we reduce with BigDecimal::add, and for large totals we use mapToLong. Moving total to an instance field compiles, but it reintroduces shared mutable state that loses updates under parallel execution and leaks between calls.
Open with
It does not compile. The lambda assigns to total, so total is not effectively final, and javac says local variables referenced from a lambda expression must be final or effectively final.
Then, if they want more
The reason is that a lambda captures a copy of a local's value when it is created, because locals live in a stack frame that may be gone when the lambda runs, possibly on another thread. If the lambda could change the variable, the copy and the variable would disagree, or threads would race on it.
So the rule forbids it for every lambda, even though this particular forEach runs sequentially. I would rewrite it as int total = orders.stream().mapToInt(Order::amount).sum(). Nothing is mutated, mapToInt avoids boxing, and it stays correct if someone makes the stream parallel.
If amount is a BigDecimal I would use map and reduce with BigDecimal.ZERO and BigDecimal::add, and if the total can get large I would use mapToLong. A plain for loop with a local is also completely fine for this.
What I would avoid is the hack of making total an instance field, or a one-element array: it compiles, but it is shared mutable state. With a parallel stream the plus-equals is a read, add and write, so updates get lost, and a field also keeps its value between calls.
About this answer
- Last updated
- 12 November 2026
- 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
- java.util.stream, package documentation, java.util.function, package 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 "What happens with this code and how would you rewrite it?": https://scrivio-interview-library.netlify.app/java/lambdas/3a5e528c10/