Java OCA OCP Practice Question 1969

Question

What is the result of executing the following application multiple times?.

package mypkg; /*from   w  w  w.ja  va2 s  . com*/
import java.util.*; 
public class Main { 
  public static void main(String... legend) { 
     Arrays.asList(1,2,3,4).stream() 
        .forEach(System.out::println); 
     Arrays.asList(1,2,3,4).parallel() 
        .forEachOrdered(System.out::println); 
  } 
} 
  • A. Only the first array is printed in the same order every time.
  • B. Only the second array is printed in the same order every time.
  • C. Both arrays are printed in the same order every time.
  • D. None of the above


D.

Note

The static method Array.asList() returns a List instance, which inherits the Collection interface.

While the Collection interface defines a stream() and parallelStream() method, it does not contain a parallel() method.

The second stream statement does not compile, and Option D is the correct answer.

If the code was corrected to use parallelStream(), then the arrays would be consistently printed in the same order, and Option C would be the correct answer.

The forEachOrdered() method forces parallel streams to run in sequential order.




PreviousNext

Related