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().
Which annotation is used to mark an interface as a functional interface in Java?
A@Function
B@FunctionalInterface
C@Lambda
D@Interface
Correct Answer:
B. @FunctionalInterface
EXPLANATION
@FunctionalInterface is the standard annotation introduced in Java 8 to explicitly mark an interface as a functional interface. It helps in compile-time checking.
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.
Which of the following is a valid functional interface that can be used with lambda expressions?
AAn interface with exactly one abstract method
BAn interface with multiple abstract methods
CAn interface with no abstract methods
DAn interface with static methods only
Correct Answer:
A. An interface with exactly one abstract method
EXPLANATION
A functional interface must have exactly one abstract method. This is the defining characteristic that allows it to be used with lambda expressions and method references.
What is the correct way to chain lambda expressions using Function interface?
Function f1 = x -> x * 2;
Function f2 = x -> x + 5;
How to apply f1 first, then f2?
Af1.andThen(f2).apply(3)
Bf1.compose(f2).apply(3)
Cf2.apply(f1.apply(3))
DA and C
Correct Answer:
D. A and C
EXPLANATION
Both andThen and explicit composition order result in applying f1 first (3*2=6, then 6+5=11), equivalent to option C.