Return to site

JAVA CERTIFICATION QUESTION: Lambda expressions and local variables in Java

· java,ocp

Given the following Capture class:

 

 

What is the result? Choose one.

* Supp 1 Supp 2 is the result.
* Supp 1 Supp 2 New is the result.
* Supp 1 New Supp 2 New is the result.
* Compilation fails due to supp1() method.
* Compilation fails due to supp2() method.

Answer: Compilation fails due to supp1() method.

Variable used in lambda expression should be final or effectively final.
In supp1(), the variable val (the one referred to in the lambda) is reassigned. This is prohibited, and the code for supp1() would not compile.