Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 59
Question ID: UKOCP83498
Consider below code:
- package com.udayankhattry.ocp;
- interface Operator<T> {
- T operate(T t);
- }
- public class Test {
- public static void main(String[] args) {
- Operator<String> opr = s -> s.toUpperCase(); //Line n1
- System.out.println(opr.operate("lambda and method references"));
- }
- }
On execution, above code prints LAMBDA AND METHOD REFERENCES on to the console.
Which of the following can replace Line n1 such that there is no change in the output?
-
A
Operator<String> opr = s.toUpperCase(); -
B
Operator<String> opr = s::toUpperCase(); -
C
Operator<String> opr = s::toUpperCase; -
D
Operator<String> opr = String::toUpperCase;
Reveal correct answer
Correct answer: D
Explanation
UKOCP83498:
This is an example of "Reference to an Instance Method of an Arbitrary Object of a Particular Type".
Parameter of lambda expression is used to invoke the toUpperCase() method and toUpperCase() method accepts no parameter, which means one parameter less than the operate method.
So, correct method reference syntax is: String::toUpperCase;
Note round brackets are not used in any of the method reference syntax.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
