Return to site

JAVA CERTIFICATION QUESTION: Lambda expressions and local variables in Java

· java

Given the following Capture class:

 

public class Capture {

    public static void main( String[] args ) {
        System.out.println( supp1().get() + supp2().get() );
    }

    static Supplier<String> supp1() {
        var val = "Supp 1 ";
        Supplier<String> s = (() -> {
            return val;
        });
        val = "Supp 1 New ";
        return s;
    }

    static Supplier<String> supp2() {
        var val = new StringBuilder( "Supp 2 " );
        Supplier<String> s = (() -> {
            return val.toString();
        });
        val.append( "New" );
        return s;
    }

}

 

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.