- 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
How to access variables from enclosing class using lambda in Java?
The variables defined by the enclosing scope of a lambda expression can be accessible within the lambda expression. A lambda expression can access to both instance, static variables and methods defined by the enclosing class. It has also access to "this" variable (both implicitly and explicitly) that can be an instance of enclosing class. The lambda expression also sets the value of an instance or static variable.
Example
interface SimpleInterface { int func(); } public class SimpleLambdaTest { static int x = 50; public static void main(String[] args) { SimpleInterface test = () -> x; // Accessing of static variable using lambda System.out.println("Accessing static variable 'x': " + test.func()); test = () -> { // Setting the value to variable using lambda return x = 80; }; System.out.println("Setting value for 'x': " + test.func()); } }
Output
Accessing static variable 'x': 50 Setting value for 'x': 80
- Related Articles
- What kind of variables can we access in a lambda expression in Java?
- How to access the members of a class from another class in Java?
- How to access Static variable of Outer class from Static Inner class in java?
- How to access variables declared in a function, from another function using JavaScript?
- How to access the object of a class without using the class name from a static context in java?
- How to access the private methods of a class from outside of the class in Java?
- Can a method local inner class access the local final variables in Java?
- How to implement LongUnaryOperator using lambda in Java?
- How to implement IntUnaryOperator using lambda in Java?
- How to implement LongConsumer using lambda in Java?
- Can we access the instance variables from a static method in Java?
- How to implement lambda expression without creating an anonymous class in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
- How to implement ToIntBiFunction using lambda expression in Java?
- How to implement ToDoubleBiFunction using lambda expression in Java?

Advertisements