Java Reference
In-Depth Information
Variable Capture
Like a local and anonymous inner class, a lambda expression can access effectively final local variables. A local
variable is effectively final in the following two cases:
final .
It is declared
final , but initialized only once.
In the following snippet of code, the msg variable is effectively final, as it has been declared final. The lambda
expression accesses the variable inside its body.
It is not declared
public Printer test() {
final String msg = "Hello"; // msg is effectively final
Printer printer = msg1 -> System.out.println( msg + " " + msg1);
return printer;
}
In the following snippet of code, the msg variable is effectively final, as it is initialized once. The lambda
expression accesses the variables inside its body.
public Printer test() {
String msg = "Hello"; // msg is effectively final
Printer printer = msg1 -> System.out.println( msg + " " + msg1);
return printer;
}
The following snippet of code is a slight variation of the above example. The msg variable is effectively final, as it
has been initialized only once.
public Printer test() {
String msg;
msg = "Hello"; // msg is effectively final
Printer printer = msg1 -> System.out.println( msg + " " + msg1);
return printer;
}
In the following snippet of code, the msg variable is not effectively final as it is assigned a value twice. The lambda
expression is accessing the msg variable that generates a compile-time error.
public Printer test() {
// msg is not effectively final as it is changed later
String msg = "Hello";
// A compile-time error as a lambda expression can access only
// effectively final local variables and the msg variable is not
// effectively final as it is changed afterwards.
 
Search WWH ::




Custom Search