How can a Lambda expression access variables outside its scope? What is the concept behind it?

A lambda expression can read local variables from its enclosing scope through a mechanism called variable capture, but only if those variables are final or effectively final, meaning their value is never changed after initialization.

Key Points

Example

In int threshold = 10; list.stream().filter(x -> x > threshold).collect(...), the lambda captures threshold's value (10) at creation time; if threshold were reassigned anywhere afterward, the code wouldn't even compile.

int threshold = 10;

List<Integer> nums = Arrays.asList(5, 12, 8, 20);

List<Integer> aboveThreshold = nums.stream()
        .filter(n -> n > threshold)
        .collect(Collectors.toList());

Interview Tip

A concise interview answer is

A lambda can read local variables from its enclosing scope, but only if they're final or effectively final, because Java captures them by value as a snapshot at creation time. That restriction exists so the lambda behaves predictably even if it runs later or on another thread — instance and static fields don't have this limitation since they're accessed through the object or class instead of being copied.

Last updated: 16 July 2026

Previous question: Can you use this and super in a lambda expression? Why or why not?

Next question: Can a Lambda expression throw an exception? How can you handle exceptions in a Lambda?

More Java 8 interview questions

All Java 8 questions