Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 25
Question ID: UKOCP13183
Given code:
- package com.udayankhattry.ocp;
- import java.util.function.UnaryOperator;
- public class Test {
- public static void main(String[] args) {
- UnaryOperator<String> opr = s -> s.toString().toUpperCase(); //Line n1
- System.out.println(opr.apply(new StringBuilder("Hello"))); //Line n2
- }
- }
What is the result?
- A Compilation error at Line n1
- B Compilation error at Line n2
- C Hello
- D HELLO
Reveal correct answer
Correct answer: B
Explanation
UKOCP13183:
interface UnaryOperator<T> extends Function<T, T>, so its apply function has the signature: T apply(T).
In this case, UnaryOperator<String> is used and hence apply method will have the signature: String apply(String).
Lambda expression s -> s.toString().toUpperCase() is the correct implementation of String apply(String) method and hence there is no issue with Line n1.
But at Line n2, argument passed to apply method is of StringBuilder type and not String type and hence Line n2 causes compilation error.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
