Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 107
Question ID: UKOCP26430
Given code:
- package com.udayankhattry.ocp;
- import java.util.stream.Stream;
- public class Test {
- public static void main(String[] args) {
- Stream.of()
- .map(s -> s.reverse())
- .forEach(System.out::println);
- }
- }
What is the result?
- A Compilation error
- B NullPointerException is thrown at runtime
- C ClassCastException is thrown at runtime
- D Program executes successfully but nothing is printed on to the console
Reveal correct answer
Correct answer: A
Explanation
UKOCP26430:
Stream.of() returns blank stream. As Type of stream is not specified, stream is of 'Stream<Object>', each element of the stream is considered to be of 'Object' type.
map method in this case accepts Function<? super Object, ? extends R>.
There is no 'reverse()' method in Object class and hence lambda expression causes compilation failure.
To resolve compilation error, you may specify type just before the of() method:
- Stream.<StringBuilder>of()
- .map(s -> s.reverse())
- .forEach(System.out::println);
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
