Java - What is the output: forward referencing of variable?

Question

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);
}


Click to view the answer

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

Note

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.

Related Quiz