Scope of Variables in Lambda Expressions
In this lesson, you will learn about the scope of variables inside lambda expressions.
Table of Contents
Variable scope
Inside lambda expressions, we can access all the variables that are in the class scope.
Local Variable: A variable declared inside the method's body is called a local variable. You can use this variable only within that method; the other methods in the class aren’t even unaware that the variable exists.
Instance variable: A variable declared inside the class but outside the method's body is called an instance variable, not declared as static.
Static variable: A variable declared as static is called a static variable.
Example code
Here's an example that demonstrates the scope of variables in lambda expressions.
@FunctionalInterface
interface MyFunctionalInterface {
void myMethod();
}
public class VariablesScope {
private static final int staticVariable = 10;
private final int instanceVariable = 20;
public static void main(String[] args) {
VariablesScope example = new VariablesScope();
example.lambdaScopeExample();
}
public void lambdaScopeExample() {
int localVariable = 30;
// Lambda expression accessing local, instance, and static variables
MyFunctionalInterface myLambda =
() -> {
System.out.println("Local variable: " + localVariable);
System.out.println("Instance variable: " + instanceVariable);
System.out.println("Static variable: " + staticVariable);
};
myLambda.myMethod();
}
}
In this example, we have a class LambdaVariablesExample
that contains three types of variables: staticVariable
(a static variable), instanceVariable
(an instance variable), and localVariable
(a local variable within the lambdaScopeExample
method).
The MyFunctionalInterface
is a functional interface with a single abstract method myMethod()
, which is implemented using a lambda expression in the lambdaScopeExample
method.
Inside the lambda expression, we access the localVariable
, instanceVariable
, and staticVariable
from the enclosing class. The lambda expression prints the values of these variables using System.out.println()
.
When we run the program, the output will be:
Local variable: 30
Instance variable: 20
Static variable: 10
This example demonstrates that lambda expressions can access local, instance, and static variables from their enclosing scope. However, it's important to note that lambda expressions can only effectively access final local variables, meaning variables that are not reassigned after initialization.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.