Java - What is the output: Lambda Expressions Variable Capture?

Question

What is the output of the following code?

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

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

    msg = "Hi"; // msg is changed
    printer.print("asf");

  }
}

interface Printer {
  void print(String msg);
}


Click to view the answer

A compile-time error
Printer printer = msg1 -> System.out.println(msg + " " + msg1);
msg = "Hi"; // msg is changed

Note

A compile-time error as a lambda expression can access only effectively final local variables.

The msg variable is not effectively final as it is changed afterwards.

Related Quiz