- 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
What kind of variables can we access in a lambda expression in Java?
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
Advertisements