Java OCA OCP Practice Question 2864

Question

What is the result of executing the following program?

import java.util.*; 
import java.util.concurrent.*; 
import java.util.stream.*; 

public class Main { 
   static int counter = 0; 
    public static void main(String[] args) throws InterruptedException,  
    ExecutionException { // w w w . j  a va 2 s .  com
      ExecutorService service = Executors.newSingleThreadExecutor(); 
      List<Future<?>> results = new ArrayList<>(); 
      IntStream.iterate(0,i -> i+1).limit(5).forEach( 
            i -> results.add(service.execute(() -> counter++)) // n1 
      ); 
      for(Future<?> result : results) { 
         System.out.print(result.get()+" "); // n2 
      } 
      service.shutdown(); 
   } 
} 
  • A. It prints 0 1 2 3 4
  • B. It prints 1 2 3 4 5
  • C. It prints null null null null null
  • D. It hangs indefinitely at runtime.
  • E. The output cannot be determined.
  • F. The code will not compile because of line n1.
  • G. The code will not compile because of line n2.


F.

Note

The key to solving this question is to remember that the execute() method returns void, not a Future object.

Therefore, line n1 does not compile and F is the correct answer.

If the submit() method had been used instead of execute(), then C would have been the correct answer, as the output of submit(Runnable) task is a Future<?> object which can only return null on its get() method.




PreviousNext

Related