Java OCA OCP Practice Question 1709

Question

What is true of the following code?

Stream<Character> stream = Stream.of('c', 'b', 'a');       // lin1
stream.sorted().findAny().ifPresent(System.out::println);  // lin2
  • A. It is guaranteed to print the single character a.
  • B. It can print any single character of a, b, or c.
  • C. It does not compile because of line lin1.
  • D. It does not compile because of line lin2.


B.

Note

Character objects are allowed in a Stream, so line lin1 compiles, making Option C incorrect.

Line lin2 also compiles since findAny() returns an Optional and ifPresent() is declared on Optional.

Therefore, Option D is also incorrect.

Now let's look at the Stream.

The source has three elements.

The intermediate operation sorts the elements and then we request one from findAny().

The findAny() method is not guaranteed to return a specific element.

Since we are not using parallelization, it is highly likely that the code will print a.

However, you need to know this is not guaranteed, making Option B the answer.




PreviousNext

Related