Java - What is the output: lambda expression effectively final variable?

Question

What is the output of the following code?

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

    Printer printer = msg1 ->  {
            msg = "Hi " + msg1; // A compile-time error. Attempting to modify msg.
            System.out.println(msg);
    };
    printer.print("asf");

  }
}

interface Printer {
  void print(String msg);
}


Click to view the answer

msg = "Hi " + msg1; // A compile-time error. Attempting to modify msg.

Note

The lambda expression accesses the local variable msg.

Any local variable accessed inside a lambda expression must be effectively final.

The lambda expression attempts to modify the msg variable inside its body that causes the compile-time error.

Related Quiz