GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.geeksforgeeks.org — Lambda Expression Variable Capturing with Examples - GeeksforGeeks Lambda Expression Variable Capturing with ExamplesLast Updated : 13 Jul, 2026 Variable capturing allows a lambda expression to access variables declared outside its own body, such as local, instance, and static variables. This feature enables lambdas to use values from their enclosing scope while following specific rules to ensure consistent and predictable behavior.
Variable CapturingVariable Capturing allows a lambda expression to access variables, methods, and fields from its enclosing scope. It enables lambdas to work with existing data without explicitly passing every value as a parameter.
Types of Variables Captured in LambdasLambda expressions can capture three types of variables from their enclosing scope: 1. Capturing Instance VariablesA lambda expression can directly access the instance variables of its enclosing object. Since instance variables belong to the object rather than the method, they can also be modified inside the lambda
Output 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. 2. Capturing Static VariablesStatic variables belong to the class instead of individual objects. Lambda expressions can access and modify static variables without any restrictions related to variable capturing.
Output Counter: 6 Explanation: The lambda directly modifies the static variable counter, since it is shared across all instances of the class. 3. Capturing Local VariablesA lambda expression can capture local variables declared in the enclosing method. However, these variables must be final or effectively final, meaning their value cannot change after initialization.
Output 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. Why Must Local Variables Be Final or Effectively Final?Unlike instance and static variables, local variables exist only while the method is executing. A lambda expression may continue to exist even after the enclosing method has finished execution. To avoid inconsistent values and unexpected behavior, Java allows lambdas to capture only final or effectively final local variables.
Output Value: 0 Value: 1 Value: 2 Explanation: Each lambda captures a different copy of the variable temp (which is effectively final). Comment Explore |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |