- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences between Lambda Expressions and Closures in Java?
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
- Related Articles
- Differences between Lambda Expression and Method Reference in Java?
- Differences between anonymous class and lambda expression in Java?\n
- What are lambda expressions in Java?
- Are lambda expressions objects in Java?
- How to debug lambda expressions in Java?
- What are block lambda expressions in Java?
- Why we use lambda expressions in Java?
- What are lambda expressions and how to use them in Java?
- Lambda Expressions in C#
- What are the characteristics of lambda expressions in Java?
- What is the syntax for lambda expressions in Java?
- What are the advantages of Lambda Expressions in Java?\n
- How to implement the listeners using lambda expressions in Java?
- Java Program to initialize a HashMap with Lambda Expressions
- How can we use lambda expressions with functional interfaces in Java?

Advertisements