Course contentsShow
← Java
Lesson 1718 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

What Is Variable Capture in Lambdas?

Understand how lambdas can reference variables from their enclosing scope and the concept of closure in Java.

What Is Variable Capture in Lambdas?

You'll learn how lambdas can "remember" and use variables from the surrounding code where they're defined.

The Core Idea

When you write a lambda expression inside a method, that lambda can access variables from the enclosing scope—meaning variables declared in the surrounding method or class. This ability to "capture" and reference external variables is called variable capture, and the lambda with its captured variables forms what's known as a closure.

Think of it like taking a snapshot: the lambda captures the values of local variables at the moment it's created and carries them along wherever it goes, even after the original method has finished executing.

How It Works

int multiplier = 10;

Function<Integer, Integer> multiply = x -> x * multiplier;

System.out.println(multiply.apply(5)); // 50

Here, the lambda captures multiplier from its enclosing scope. The lambda "closes over" this variable, creating a closure.

The "Effectively Final" Requirement

Java requires captured variables to be effectively final—meaning they cannot be modified after the lambda is defined:

int base = 100;
Consumer<Integer> printer = x -> System.out.println(x + base);

// base = 200; // ERROR: Cannot modify captured variable

This restriction exists because the lambda might execute later or in different contexts, and Java needs to guarantee the captured value remains consistent.

The Analogy

Think of a lambda as a traveler packing a suitcase. It can pack copies of local variables (the snapshot), but those items must be locked in the suitcase—you can't change them once packed, ensuring the traveler always has the original items no matter where they go.

Key Takeaway: Lambdas can capture and reference variables from their enclosing scope, but those variables must be effectively final. This combination of the lambda and its captured context is called a closure.