Java SE 8 Programmer II — Question 12
Given the code fragment:
List<Integer> codes = Arrays.asList (10, 20);
UnaryOperator<Double> uo = s -> s +10.0;
codes.replaceAll(uo);
codes.forEach(c -> System.out.println(c));
What is the result?
Answer options
- A. 20.0 30.0
- B. 10.0 20.0
- C. A compilation error occurs.
- D. A NumberFormatException is thrown at run time.
Correct answer: C
Explanation
The correct answer is C because the replaceAll method expects a UnaryOperator that operates on the same type as the list, which is Integer, but a UnaryOperator<Double> is provided instead, leading to a compilation error. Options A and B are incorrect because they suggest valid output, which cannot occur due to the compilation error. Option D is also wrong as it states a runtime exception occurs, which is only relevant if the code could compile.