Which of the following correctly uses a method reference as an alternative to a lambda expression?
ASystem.out::println instead of (x) -> System.out.println(x)
BString::length instead of (s) -> s.length()
CInteger::parseInt instead of (s) -> Integer.parseInt(s)
DAll of the above
Correct Answer:
D. All of the above
EXPLANATION
All three are valid method references that can replace their equivalent lambda expressions. Method references are a shorthand notation introduced in Java 8.
In a lambda expression, what does the arrow (->) operator represent?
AAssignment operator
BSeparation between parameters and body
CComparison operator
DLogical AND operator
Correct Answer:
B. Separation between parameters and body
EXPLANATION
The arrow (->) in lambda expressions separates the parameter list on the left from the method body on the right. It's a syntax element specific to lambda expressions.
Consider the code: List names = Arrays.asList("Alice", "Bob"); names.forEach(name -> System.out.println(name)); What type of functional interface is used in forEach?
AFunction
BConsumer
CSupplier
DPredicate
Correct Answer:
B. Consumer
EXPLANATION
forEach accepts a Consumer functional interface. Consumer<T> takes an input and performs an action without returning anything, which matches the System.out.println action.
What is the purpose of a Predicate functional interface in Java?
ATo transform one type of object to another
BTo perform an action without returning a value
CTo test a condition and return a boolean value
DTo supply a value without taking any input
Correct Answer:
C. To test a condition and return a boolean value
EXPLANATION
Predicate<T> is a functional interface that takes a single input of type T and returns a boolean. It's commonly used for filtering operations in streams.