What will happen if you try to access a local variable from an enclosing scope that is not final or effectively final in a lambda expression?
AIt will compile and run successfully
BCompilation error: variable must be final or effectively final
CRuntime exception will be thrown
DThe variable value will be copied
Correct Answer:
B. Compilation error: variable must be final or effectively final
EXPLANATION
Lambda expressions can only access local variables that are final or effectively final. This is because lambda expressions are translated to methods that need access to stable variable values.
Consider a lambda expression: (String s) -> s.length(). What is the correct functional interface for this?
AFunction
BSupplier
CConsumer
DPredicate
Correct Answer:
A. Function
EXPLANATION
Function<String, Integer> takes a String input and returns an Integer (the length). This matches the lambda that takes a String parameter and returns s.length().
What is the return type of a lambda expression (x, y) -> x + y where x and y are integers?
Avoid
BInteger
CDepends on the functional interface it's assigned to
Dint
Correct Answer:
C. Depends on the functional interface it's assigned to
EXPLANATION
The return type of a lambda expression is inferred from the functional interface it's assigned to. The same lambda can return Integer or int depending on the context.