What kind of variables can we access in a lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

The lambda expressions consist of two parts, one is parameter and another is an expression and these two parts have separated by an arrow (->) symbol. A lambda expression can access a variable of it's enclosing scope. 

A Lambda expression has access to both instance and static variables of it's enclosing class and also it can access local variables which are effectively final or final.

Syntax

( argument-list ) -> expression

Example

interface TestInterface {
   void print();
}
public class LambdaExpressionTest {
   int a; // instance variable
   static int b; // static variable
   LambdaExpressionTest(int x) {    // constructor to initialise instance variable
      this.a = x;
   }
   void show() {
      // lambda expression to define print() method
      TestInterface testInterface = () -> {
      // accessing of instance and static variable using lambda expression
         System.out.println("Value of a is: "+ a);
         System.out.println("Value of b is: "+ b);
      };
      testInterface.print();
   }
   public static void main(String arg[]) {
      LambdaExpressionTest test = new LambdaExpressionTest(10);
      test.show();
   }
}

Output

Value of a is: 10
Value of b is: 0
raja
Published on 11-Dec-2019 17:00:52
Advertisements