Java OCA OCP Practice Question 2836

Question

Which lines need to be changed to make the code compile? (Choose all that apply.)

ExecutorService service = Executors.newSingleThreadScheduledExecutor(); 

service.scheduleWithFixedDelay(() -> { // w1 
      System.out.println("start"); 
      return null; // w2 
   }, 0, 1, TimeUnit.MINUTES); /*from w ww .ja  v a  2s . c  om*/

Future<?> result = service.submit(() -> System.out.println("command")); // w3 

System.out.println(result.get()); // w4 
  • A. It compiles and runs without issue.
  • B. Line w1
  • C. Line w2
  • D. Line w3
  • E. Line w4
  • F. It compiles but throws an exception at runtime.


B, C.

Note

The code does not compile, so A and F are incorrect.

The first problem is that although a ScheduledExecutorService is created, it is assigned to an ExecutorService.

Since scheduleWithFixedDelay() does not exist in ExecutorService, line w1 will not compile, and B is correct.

The second problem is that scheduleWithFixedDelay()supports only Runnable, not Callable, and any attempt to return a value is invalid in a Runnable lambda expression; therefore line w2 will also not compile and C is correct.

The rest of the lines compile without issue, so D and E are incorrect.




PreviousNext

Related