![]() |
VOOZH | about |
When we write a lambda expression in Java, it can access variables that are defined outside its own block, such as variables from the surrounding method or class. This process is called variable capturing. However, there are a few important rules about which variables can be used and how they can be modified.
Lambda expressions can capture three types of variables from their enclosing scope:
A lambda can directly access instance variables of its enclosing class.
Instance variable: 10
Explanation: The lambda expression captures the instance variable number from the current object using this.number. It can modify it if not declared final.
Static variables belong to the class rather than any instance, and Lambda Expression can access and modify them freely.
Counter: 6
Explanation: The lambda directly modifies the static variable counter, since it is shared across all instances of the class.
Lambda Expression can capture local variables declared in the enclosing method. However, these variables must be effectively final — meaning they are not modified after being assigned.
Local variable captured: 20
Explanation: The variable num is captured by the lambda. Since it is not modified anywhere after initialization, it is considered effectively final.
Lambda expression can outlive their defining method. To ensure consistency, they can capture only local variables that are final or effectively final, guaranteeing predictable, unchanging values.
Value: 0 Value: 1 Value: 2
Explanation: Each lambda captures a different copy of the variable temp (which is effectively final).
If we used i directly without creating a separate variable, it would cause a compile-time error because i changes in each loop iteration.