Effectively final variables in lambdas
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A lambda may read a local variable of the method around it only if that variable is effectively final: it gets a value once and is never assigned again. The lambda keeps a copy of the value, so Java forbids any change that would make the copy and the variable disagree.
What effectively final means
A variable is effectively final when it is never changed after it is first given a value. Lambdas may use local variables only if they are final or effectively final.
A local variable is declared inside a method, including the method's parameters. When a lambda uses one, the lambda is said to capture it.
String city = "Pune"; // never changed: effectively finalRunnable show = () -> System.out.println(city); // fineint total = 0;Runnable bad = () -> System.out.println(total);// error: local variables referenced from a lambda expression must be final or effectively finaltotal += 5; // this later line is the reasonA variable is effectively final when it is assigned exactly once and never changed afterwards, even though it has no final keyword. A quick test: if you could add final to its declaration and the code would still compile, it is effectively final.
The compiler checks the whole method, not only the lines before the lambda. An assignment after the lambda, or a count++ anywhere, makes the variable not effectively final, and every lambda that uses it fails to compile.
String city = "Pune";and never changed: effectively final, a lambda may use it.int total = 0;followed later bytotal += 5;: not effectively final.- The variable of an enhanced
forloop is a fresh variable on each pass, so it is effectively final. - The
iof a classicfor (int i = 0; ...; i++)loop changes, so it is not.
The error and its usual fixes
When a lambda uses a variable that changes, javac reports: "local variables referenced from a lambda expression must be final or effectively final". The arrow points at the use inside the lambda, even if the change happens somewhere else.
Example 1 · Error: changing a counter inside forEach
import java.util.List;
public class CounterErrorDemo { public static void main(String[] args) { List<Integer> marks = List.of(82, 31, 64, 28, 90); int passed = 0; marks.forEach(m -> { if (m >= 35) { passed++; } }); System.out.println("Passed: " + passed); }}CounterErrorDemo.java:9: error: local variables referenced from a lambda expression must be final or effectively final
passed++;
^
1 errorWhat this code does
passed++assigns a new value to a local variable, sopassedis not effectively final, and a lambda may not use it.- For one total, a plain loop is the clean fix:
for (int m : marks) if (m >= 35) passed++;. The next example shows other fixes.
Example 2 · Fixes: a plain loop and a copied value
import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;
public class CaptureFixDemo { public static void main(String[] args) { List<Integer> marks = List.of(82, 31, 64, 28, 90);
int passed = 0; for (int m : marks) { // no lambda, so passed may change if (m >= 35) { passed++; } } System.out.println("Passed: " + passed);
List<Supplier<String>> hallTickets = new ArrayList<>(); for (int i = 0; i < 3; i++) { int seat = 101 + i; // a new effectively final variable on every pass hallTickets.add(() -> "Seat " + seat); } for (Supplier<String> t : hallTickets) { System.out.println(t.get()); }
String exam = "Physics"; // assigned once: effectively final Supplier<String> header = () -> exam + " - Hall 3"; System.out.println(header.get()); }}Passed: 3 Seat 101 Seat 102 Seat 103 Physics - Hall 3
What this code does
ichanges, so a lambda cannot use it.seatis declared inside the loop, so each pass creates a new variable that is assigned once, and each lambda captures its own copy.examis never reassigned, so it is effectively final without thefinalkeyword.
The most common cause is counting or summing inside forEach: list.forEach(m -> total += m);. The lambda would have to change total, which it is not allowed to do. Pick the fix by what you need. To compute one result from a list, use a plain for loop; it has no such limit. To use a changing value inside a lambda, copy it into a new variable first: int roll = i; inside the loop, then use roll. To keep state that really must change across calls, store it in a field of an object.
Fix the error
Fix the captured variable
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Add up the marks.
Error
TotalFix.java:7: error: local variables referenced from a lambda expression must be final or effectively final
marks.forEach(m -> total += m);Why lambdas capture values, not variables
A local variable lives in the method's stack frame, the memory for one method call, and it is gone when the method returns. A lambda is an object that can live much longer: it can be stored, returned or run later.
Example 3 · Values are copied, but objects can still change
import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;
public class CaptureObjectDemo { public static void main(String[] args) { List<String> cart = new ArrayList<>(); int itemsAtStart = cart.size();
Supplier<String> summary = () -> "Cart " + cart + ", started with " + itemsAtStart + " item(s)";
cart.add("Pen"); // allowed: the list changes, the variable does not cart.add("Notebook"); System.out.println(summary.get());
Runnable addBag = () -> cart.add("Bag"); // also allowed inside a lambda addBag.run(); System.out.println(summary.get()); }}Cart [Pen, Notebook], started with 0 item(s) Cart [Pen, Notebook, Bag], started with 0 item(s)
What this code does
- The lambda copied the reference in
cartand the value 0 initemsAtStartwhen it was created. Later calls see the list's current contents, butitemsAtStartstays 0. cart.addchanges the object, not the variablecart, socartis still effectively final and both lambdas compile.
So Java copies the variable's value into the lambda object when the lambda is created. If the variable could still change, the copy and the original would silently disagree, and code would print old values. Making the rule "no changes at all" removes that confusion.
For an object variable, the value that is copied is the reference. The reference cannot change, but the object it points to can. That is why list.add(x) inside a lambda compiles: the lambda never assigns a new list, it only calls a method on the same one.
ArrayList can still grow.Fields and this: lambda versus anonymous class
Fields are different. A lambda inside an instance method can read and change the object's fields, because it captures this, and a field lives in the object on the heap, not in the stack frame. Static fields can always be changed too.
Example 4 · Fields and this: lambda versus anonymous class
import java.util.function.Supplier;
class Classroom { private final String name; private int questionsAsked = 0; // a field: lambdas may change it
Classroom(String name) { this.name = name; }
void demo() { Runnable ask = () -> questionsAsked++; ask.run(); ask.run(); System.out.println("Questions asked: " + questionsAsked);
Supplier<String> fromLambda = () -> this.toString(); Supplier<String> fromAnonymous = new Supplier<String>() { @Override public String get() { return this.toString() + " inside " + Classroom.this.name; }
@Override public String toString() { return "helper object"; } }; System.out.println("Lambda this: " + fromLambda.get()); System.out.println("Anonymous this: " + fromAnonymous.get()); }
@Override public String toString() { return "Classroom " + name; }}
public class ThisDemo { public static void main(String[] args) { new Classroom("CSE-A").demo(); }}Questions asked: 2 Lambda this: Classroom CSE-A Anonymous this: helper object inside CSE-A
What this code does
questionsAsked++compiles inside the lambda because it is a field: the lambda changes the object throughthis, not a local variable.- In the lambda,
thisis theClassroom. In the anonymous class,thisis the anonymous object, andClassroom.thisreaches the outer one.
Inside a lambda, this means the object of the enclosing method, the same as one line outside the lambda. Inside an anonymous class, this means the new anonymous object itself; to reach the outer object you write Outer.this. Anonymous classes follow the same effectively final rule for local variables. One more difference: an anonymous class may declare a variable with the same name as a local variable outside it, but a lambda may not, because a lambda body is in the same scope as the code around it.
Trap: the one-element array counter
A common workaround is int[] count = {0}; and then count[0]++ inside the lambda. It compiles, because the array reference never changes; only its contents do.
Example 5 · Trap: the shared one-element array
import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;
public class ArrayCounterTrapDemo { public static void main(String[] args) { List<String> names = List.of("Rohan", "Kavya", "Divya"); int[] token = {0}; // the "workaround" List<Supplier<String>> slips = new ArrayList<>();
for (String name : names) { token[0]++; slips.add(() -> name + " gets token " + token[0]); }
// the slips are printed later, after the loop has finished for (Supplier<String> slip : slips) { System.out.println(slip.get()); } }}Rohan gets token 3 Kavya gets token 3 Divya gets token 3
What this code does
- Every lambda captured the same array, not the number it held at that moment. When the slips are printed,
token[0]is already 3, so all three people get token 3. - It compiled without any warning, which is exactly why this workaround is risky. Copying the number into a new local variable,
int myToken = token[0];, gives each lambda its own value.
It hides real bugs. Every lambda created in a loop shares the same array, so lambdas that run later all see its final value. If the lambda later runs on several threads at once, two threads can read the same old value and one increment is lost. And the code says "this lambda changes outside state", which makes it hard to reason about. Use it only when you understand those risks. Better fixes: a plain loop for one total, a copied local variable for "the value at this moment", or a small class with a field for real state. The Multithreading & Concurrency section covers AtomicInteger, the safe counter for many threads.
Next step
Check your understanding
11 quick questions