Java - Accessing Local and Instance Variables Inside Lambda Expressions


createLambda() method uses a lambda expressions to create an instance of the Printer functional interface.

The lambda expression uses the method's parameter incrementBy.

The main() method creates two instances of the VariableCapture class and calls the createLambda() method.

The output shows that the lambda expression captures the incrementBy value and it increments the counter instance variable every time it is called.


class Main {
  private int counter = 0;

  public static void main(String[] args) {
    Main vc1 = new Main();
    Main vc2 = new Main();

    // Create lambdas
    Printer p1 = vc1.createLambda(1);/*from  ww w .j  ava2  s  .c  om*/
    Printer p2 = vc2.createLambda(100);

    // Execute the lambda bodies
    p1.print("Lambda #1");
    p2.print("Lambda #2");
    p1.print("Lambda #3");
    p2.print("Lambda #4");
    p1.print("Lambda #5");
    p2.print("Lambda #6");

  public Printer createLambda(int incrementBy) {
    Printer printer = msg -> {
      // Accesses instance and local variables
      counter += incrementBy;
      System.out.println(msg + ": counter = " + counter);

    return printer;

interface Printer {
  void print(String msg);


Related Topic