Variable Capture

Java-Variable Capture

Variable Capture

A lambda expression can use an instance or static variable defined by its enclosing class. A lambda expression also has access to this keyword, which refers to the invoking instance of the lambda expression’s enclosing class. Thus, a lambda expression can obtain or set the value of an instance or static variable and call a method defined by its enclosing class.

When a lambda expression uses a local variable from its enclosing scope, a special situation is created that is referred to as a variable capture. In this case, a lambda expression may only use local variables that are effectively final. An effectively final variable is one whose value does not change after it is first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error. It is important to understand that a local variable of the enclosing scope cannot be modified by the lambda expression.

For example, in the following program(Program Two), data is effectively final and can, therefore, be used inside myi. However, if data were to be modified, either inside the lambda or outside of it, data would lose its effectively final status. This would cause an error, and the program would not compile. It is important to emphasize that a lambda expression can use and modify an instance variable from its invoking class. It just can’t use a local variable of its enclosing scope unless that variable is effectively final.

Program

Variable Capture

Program Source

interface MyInterface{
    
    void myFunction();
}
public class Javaapp {
    
    int data = 100;
    
    public static void main(String[] args) {
        
        Javaapp jp = new Javaapp();
       
        MyInterface myi = ()->{
            
            System.out.println("data : "+jp.data);
            jp.data+=100;
            System.out.println("data : "+jp.data);
        };
        myi.myFunction();
        jp.data+=100;
        System.out.println("data : "+jp.data);
    }
}

Program Source

interface MyInterface{
    
    void myFunction();
}
public class Javaapp {
       
    public static void main(String[] args) {
        
        int data = 100;
       
        MyInterface myi = ()->{
            
            System.out.println("data : "+data);
            
        };
        myi.myFunction();
        data+=100;
        System.out.println("data : "+data);
    }
}

Leave a Comment