- 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
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
- Related Articles
- How can we write a multiline lambda expression in Java?
- How can we pass lambda expression in a method in Java?
- How can we write Callable as a lambda expression in Java?
- Can we access the instance variables from a static method in Java?
- How to access variables from enclosing class using lambda in Java?
- How can we iterate the elements of List and Map using lambda expression in Java?
- How many parameters can a lambda expression have in Java?
- What is a target type of lambda expression in Java?
- Can we sort a list with Lambda in Java?
- What is the data type of a lambda expression in Java?
- Lambda expression in Java 8
- How to write a conditional expression in lambda expression in Java?
- What kind of variables/methods defined in an interface in Java 9?
- Can we cast reference variables in Java?
- Can we serialize static variables in Java?

Advertisements