Java - Lambda Expressions Variable Capture

Introduction

A lambda expression can access effectively final local variables.

A local variable is effectively final in the following two cases:

  • It is declared final.
  • It is not declared final, but initialized only once.

Example

In the following code, the msg variable is effectively final, as it has been declared final.

The lambda expression accesses the variable inside its body.

class Main {
  public static void main(String[] args) {
    final String msg = "Hello"; // msg is effectively final

    Printer printer = msg1 -> System.out.println(msg + " " + msg1);

  }
}

interface Printer {
  void print(String msg);
}

In the following code, the msg variable is effectively final, as it is initialized once.

The lambda expression accesses the variables inside its body.

class Main {
  public static void main(String[] args) {
    String msg = "Hello"; // msg is effectively final

    Printer printer = msg1 -> System.out.println(msg + " " + msg1);

  }
}

The following code, msg variable is effectively final, as it has been initialized only once.

String msg;
msg = "Hello"; // msg is effectively final

Printer printer = msg1 -> System.out.println(msg + " " + msg1);

Related Topic