Java OCA OCP Practice Question 2514

Question

Which of the following are true? (Choose all that apply.)

private static void magic(Stream<Integer> s) { 
    Optional o = s.filter(x -> x < 5).limit(3).max((x, y) -> x-y); 
    System.out.println(o.get()); 
} 
  • A. magic(Stream.empty()); runs infinitely.
  • B. magic(Stream.empty()); throws an exception.
  • C. magic(Stream.iterate(1, x ->> x++)); runs infinitely.
  • D. magic(Stream.iterate(1, x ->> x++)); throws an exception.
  • E. magic(Stream.of(5, 10)); runs infinitely.
  • F. magic(Stream.of(5, 10)); throws an exception.
  • G. The method does not compile.


B, F.

Note

Calling get() on an empty Optional causes an exception to be thrown, making options B and F correct.

Option C is incorrect because the infinite stream is made finite by the intermediate limit() operation.

Options A and E are incorrect because the source streams are not infinite.

Therefore, the call to max() sees only three elements and terminates.




PreviousNext

Related