Differences between Lambda Expressions and Closures in Java?

Java 8Object Oriented ProgrammingProgramming

Java supports lambda expressions but not the Closures. A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class. It means that Closures can access variables not defined in its parameter list and also assign it to a variable.

Syntax

([comma seperated parameter-list]) -> {body}

In the below example, the create() method has a local variable "value" with a short life and disappears when we exit the create() method. This method returns the closure to the caller in the main() method after that method has finished. In this process, it removes the variable "value" from its stack and the lambda expression has executed.

Example

public class LambdaExpressionClosureTest {
   public static void main(String[] args) {
      Runnable runnable = create();
      System.out.println("In main() method");
      runnable.run();
   }
   public static Runnable create() {
      int value = 100;
// Lambda Expression
      Runnable runnable = () -> System.out.println("The value is: " + value);
      System.out.println("In create() method");
      return runnable;
   }
}

Output

In create() method
In main() method
The value is: 100
raja
Published on 11-Dec-2019 10:23:29
Advertisements