Java OCA OCP Practice Question 1591

Question

How many lines does this code output?

List<String> list = new LinkedList<>();
list.add("A");
list.add("B");
 
list.stream().forEach(s -> System.out.println(s));
list.stream().forEach(s -> System.out.println(s));
  • A. Two
  • B. Four
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


B.

Note

This code adds two elements to a list.

It then gets a stream and iterates through the list, printing two lines.

The last line does the same thing again.

Since a fresh stream is created, we are allowed to iterate through it, and Option B is correct.




PreviousNext

Related