Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
Variables and lambdas for the OCP 21 exam: inferring parameter types, var, final and annotations on parameters, consistent parameter formats, locals inside lambda blocks and name clashes, and which instance, static and local variables a lambda body may reference.
kvi5hnuCode Sprout team member7 min readOn this page
Variables show up in three places around a lambda: in its parameter list, as locals inside its body, and as variables from the surrounding code that the body refers to. Each place has its own rules, and the exam likes to mix them.
The parameter list
Inferring the type
Lambda parameters always have a type, even when you don't write it. The compiler takes it from the target functional interface, so you can work it out the same way:
Predicate<String> p = x -> x.isEmpty(); // x is a String
void consume(Consumer<Integer> c, int n) { c.accept(n); }
consume(v -> System.out.print(v), 42); // v is an Integer (from the parameter type)
void sortAll(List<Double> prices) {
prices.sort((a, b) -> a.compareTo(b)); // a and b are Double (from List<Double>)
}
Look at the variable's declared type, the parameter type of the method being called, or the generic type of the collection being used.
Three formats, never mixed
These three are equivalent:
Predicate<String> p1 = x -> true; // no type
Predicate<String> p2 = (var x) -> true; // var
Predicate<String> p3 = (String x) -> true; // explicit type
All the parameters of one lambda must use the same format:
(var a, b) -> "no" // DOES NOT COMPILE: var mixed with no type
(var a, Integer b) -> true // DOES NOT COMPILE: var mixed with a type
(String a, var b, Integer c) -> 1 // DOES NOT COMPILE
(Integer a, b) -> "no" // DOES NOT COMPILE: type mixed with no type
javac reports all of these as "invalid lambda parameter declaration".
Modifiers and annotations
A parameter declared with var or an explicit type behaves like a method parameter. It can take final and annotations:
prices.sort((final var a, @Deprecated var b) -> a.compareTo(b));
BiFunction<String, Integer, String> rep = (final String s, final Integer n) -> s.repeat(n);
Modifiers need a type or var to attach to, so (final a, b) -> … doesn't compile. In real code these modifiers are rare, but the exam includes them to check you know they're legal.
Locals inside the lambda body
A block body can declare its own local variables, just like any block:
BiFunction<Integer, Integer, Integer> f = (a, b) -> {
int total = a + b;
return total * 2;
};
Those variables live only inside the block. But remember from article 46: the lambda doesn't get a fresh scope for names. Its parameters and locals share the enclosing method's scope, so they can't reuse names that are already in scope there:
(a, b) -> { int a = 0; return 5; } // DOES NOT COMPILE: a is already defined (parameter)
Here's a harder example, with three separate mistakes:
public void check(int level) {
int limit = 1;
Predicate<Integer> p = level -> { // 1: level is already a method parameter
int limit = 0; // 2: limit is already a local in the method
int floor = 0;
return limit == floor;
} // 3: missing ; after the assignment statement
}
The ; inside the block ends the return statement. The assignment Predicate<Integer> p = … still needs its own semicolon after the closing brace.
Two separate lambdas in the same method can each declare a local with the same name, because their blocks don't overlap.
Variables referenced from the lambda body

| Variable | Can the lambda use it? |
|---|---|
| instance variable (field) | yes, read and write |
| static (class) variable | yes, read and write |
| method parameter | only if effectively final |
| local variable | only if effectively final |
Fields are reached through this or the class, so the lambda always sees their current value and may change them. Local variables and parameters are copied into the lambda when it's created. So, just as for local and anonymous classes (article 44), they must be final or effectively final: never assigned after initialization.
public class Bird {
private String color;
public void sing(String name) {
String volume = "loudly";
name = "Robin"; // name is now NOT effectively final
color = "red"; // fine: a field
Consumer<String> c = s ->
System.out.println(name // DOES NOT COMPILE
+ " sings " + volume // DOES NOT COMPILE
+ " in " + color); // fine
volume = "softly"; // volume is NOT effectively final either
}
}
The compiler reports the error where the lambda uses the variable, not at the assignment, and even when the assignment comes later in the method, as with volume. The assignment itself is legal. Only the combination of reassigning and capturing isn't.
More cases to know:
- Changing a captured local inside the lambda fails the same way:
Runnable r = () -> count++;doesn't compile ifcountis a local. - Declared first, assigned once later still counts as effectively final:
int base; base = 30;can be captured afterward. Using it in a lambda before it's assigned gives "variable might not have been initialized". - Classic
forloop counters change each iteration, sofor (int i = 0; …; i++) { Runnable r = () -> use(i); }doesn't compile. Copy the counter first (int step = i;). An enhancedforvariable is new in each iteration, so it can be captured. - Mutating an object is fine. If a captured local refers to a list or an array, the lambda can call
list.add(...)or changearray[0], because the variable never changes. This is a common way to keep a counter, although a field or an atomic class is usually clearer. thisfollows the enclosing method. Inside a static method there's nothis, so the lambda can't use instance fields there either.
What's current
- The effectively final rule hasn't changed through Java 25.
- Java 22 lets you name an unused lambda parameter
_((key, _) -> key). It's on the Java 25 exam, not on 1Z0-830, where_is a compile error.
Exam traps from this article
A complete example
buildTasks creates lambdas that capture an effectively final parameter, a local assigned once, and a per-iteration copy of the loop counter, while also reading and writing fields. main shows the three parameter formats, a local inside a lambda block, and an array used as a counter.
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class Solution {
private static int created; // class variable: lambdas may read and change it
private final List<String> history = new ArrayList<>(); // instance variable
private String mood = "calm";
Solution() { created++; }
List<Runnable> buildTasks(String owner, int repeats) {
String prefix = owner + ": "; // effectively final local
int base; // assigned exactly once below: still effectively final
base = repeats * 10;
List<Runnable> tasks = new ArrayList<>();
for (int i = 1; i <= repeats; i++) {
int step = i; // fresh effectively final copy for each iteration
tasks.add(() -> {
String line = prefix + "step " + step + " of " + repeats + " (base " + base + ", " + mood + ")";
history.add(line); // instance field: mutable access is fine
System.out.println(line);
});
}
mood = "busy"; // fields aren't captured by value: lambdas see the new value
return tasks;
}
public static void main(String[] args) {
Solution s = new Solution();
List<Runnable> tasks = s.buildTasks("Ana", 3);
tasks.forEach(Runnable::run);
System.out.println("history size: " + s.history.size());
// Three equivalent parameter styles: no type, var, explicit type
BiFunction<String, Integer, String> a = (t, n) -> t.repeat(n);
BiFunction<String, Integer, String> b = (var t, var n) -> t.repeat(n);
BiFunction<String, Integer, String> c = (final String t, final Integer n) -> t.repeat(n);
System.out.println(a.apply("ab", 2) + " " + b.apply("cd", 2) + " " + c.apply("ef", 2));
// A local inside a lambda block is private to that block
Consumer<String> shout = text -> {
String loud = text.toUpperCase();
System.out.println(loud + "!");
};
shout.accept("done");
// Need a counter? Mutate an object or array element, not the local variable itself
int[] calls = {0};
Supplier<Integer> counter = () -> ++calls[0];
counter.get();
counter.get();
System.out.println("counter called " + calls[0] + " times, Solution objects created: " + created);
}
}
Output:
Ana: step 1 of 3 (base 30, busy)
Ana: step 2 of 3 (base 30, busy)
Ana: step 3 of 3 (base 30, busy)
history size: 3
abab cdcd efef
DONE!
counter called 2 times, Solution objects created: 1
Points to notice:
stepis a new effectively final variable in each loop iteration, so each lambda prints its own step number. Capturingidirectly wouldn't compile.baseis declared, then assigned exactly once, so it's still effectively final.moodis a field, so the lambdas read its current value when they run,busy, even though it wascalmwhen they were created.history.add(line)and++calls[0]mutate objects. The captured variables themselves never change.(final String t, final Integer n)shows that modifiers are legal on typed parameters.
Common questions
Why are fields treated differently from locals? A lambda only stores a reference to the enclosing object (or none, for static fields), and reads the field through it at run time. Locals live on the method's stack frame, which may be gone when the lambda runs, so their values must be copied, and therefore must not change.
Is using an array as a counter good style?
It works, but it's a workaround. Prefer a field, a mutable holder object, or an AtomicInteger, especially when lambdas may run on several threads (chapter 13).
Can a lambda parameter shadow a field? Yes. Only local variables and parameters of the enclosing method are off-limits. A parameter named like a field simply hides the field inside the lambda.
Summary
- Lambda parameter types are inferred from the target type. You may write them as untyped names,
varor explicit types, but not mixed. - With
varor a type, parameters can befinalor annotated. - Lambda parameters and block locals share the enclosing scope for names, so they can't redeclare existing locals or parameters.
- Lambdas may read and write instance and static variables freely.
- Local variables and method parameters used in a lambda must be final or effectively final. Violations are reported where the lambda uses the variable.
Practice quiz
Test yourself with the lambda variables quiz: 10 exam-style questions with explanations.
You've finished Chapter 8. Check your understanding of the whole chapter with the Chapter 8 review quiz: 20 mixed questions on lambda syntax, functional interfaces, method references, built-in and primitive functional interfaces, and variables in lambdas.
Previous: Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
Next: Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
Related reading
- Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
- Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
- Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
- Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.