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

Attempting to Modify Captured Variables

Understand why reassigning captured variables inside lambdas causes compilation errors and how to recognize these.

Attempting to Modify Captured Variables

You'll learn why trying to change captured variables inside a lambda causes a compilation error and how to spot this mistake.

The Problem: Trying to Reassign What You've Captured

When a lambda expression "captures" a local variable from its surrounding scope, Java treats that variable as if it were final. This means any attempt to reassign that variable—either inside the lambda or after it's been captured—will fail to compile.

Think of it like this: when the lambda takes a snapshot of the variable's value, the camera gets locked. You can't go back and change the original photo or the subject afterward without breaking the entire system.

Common Compilation Errors

Here are the two ways you'll trigger this error:

1. Modifying Inside the Lambda

int count = 0;
Runnable task = () -> {
    count++;  // ❌ Compilation error: cannot assign to effectively final variable
};

2. Modifying After Capture

int count = 0;
Runnable task = () -> System.out.println(count);
count++;  // ❌ Compilation error: count is no longer effectively final

Both scenarios break the "effectively final" contract. The compiler will tell you something like: "local variables referenced from a lambda expression must be final or effectively final".

How to Recognize These Errors

Watch for:

  • Reassignment operators inside lambdas: =, ++, --, +=, etc.
  • Any modification to captured variables after the lambda is defined
  • The same rules apply whether the lambda executes immediately or later

Key Takeaway: Once a variable is captured by a lambda, neither the lambda nor the surrounding code can reassign it—attempting to do so produces a compilation error that explicitly mentions the "final or effectively final" requirement.