OCP Question 6, Explanation

Given the code fragments:

class Caller implements Callable<String> {
     String str;
     public Caller (String str) {
         this.str = str;
     public String call() throws Exception {
         return str.concat ("Caller");
 class Runner implements Runnable {
     String str;
     public Runner (String str) {
         this.str = str;
     public void run() {
         System.out.println (str.concat ("Runner"));



public static void main (String[] args) throws InterruptedException, ExecutionException {
     ExecutorService exec = Executors.newFixedThreadPool(2);
     Future f1 = exec.submit(new Caller ("Call "));
     Future f2 = exec.submit(new Runner ("Run "));
     String str1 = (String) f1.get();
     String str2 = (String) f2.get();                 //line n1
     System.out.println(str1+ " : " + str2);

What is the result?

A. The program prints:
Run Runner
Call Caller : null
And the program does not terminate.

B. The program terminates after printing:
Run Runner
Call Caller : Run
C.  A compilation error occurs at line n1
D. An exception is thrown at run time


The correct answer is A.

This is what the javadoc for the ExecutorService interface says about the submit() method that’s overloaded for a Runnable arg:

So the normally terminated Runner-based task returns null. As for the overloaded-for-Callable submit(),

In principle, that’s enough to determine the program’s output. To make our inference even more conclusive and irrefutable, let’s recall that all tasks that are launched from main() or any other non-daemon thread, should be shutdown explicitly, otherwise the program will be sitting idle for as long as the JVM runs. To force the program to terminate normally, we could add this LOC to main():


On a final note please observe that the Future objects weren’t typed, that’s why we needed those two casts (on line n1 and the preceding LOC). Omitting either of them would lead to the “Object cannot be converted to String” comperr that was hinted at by option C.

Leave Comment

Your email address will not be published.