What is the output of the following code?
class Main { public static void main(String[] args) { Printer printer = msg1 -> System.out.println(msg + " " + msg1); String msg = "Hi"; // msg is changed printer.print("asf"); } } interface Printer { void print(String msg); }
//Compile time error Printer printer = msg1 -> System.out.println(msg + " " + msg1);
The code generates a compile-time error because the lambda expression accesses the msg variable that is declared lexically after its use.
In Java, forward referencing of variable names in method's scope is not allowed.
The msg variable is effectively final.