Java OCA OCP Practice Question 3109

Question

Given the definition:

class Sum implements Callable<Long> {   // LINE_DEF
    long n;/*from www . j av  a2 s .co m*/
    public Sum(long n) {
        this.n = n;
    }
    public Long call() throws Exception {
        long sum = 0;
        for(long i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
}

Given that the sum of 1 to 5 is 15, select the correct option for this code segment:

Callable<Long> task = new Sum(5);
ExecutorService es = Executors.newSingleThreadExecutor(); // LINE_FACTORY
Future<Long> future = es.submit(task);                    // LINE_CALL
System.out.printf("sum of 1 to 5 is %d", future.get());
es.shutdown();
  • a) this code results in a compiler error in the line marked with the comment LINE_DEF
  • b) this code results in a compiler error in the line marked with the comment LINE_FACTORY
  • c) this code results in a compiler error in the line marked with the comment LINE_CALL
  • d) this code prints: sum of 1 to 5 is 15


d)

Note

this code correctly uses Callable<T>, ExecutorService, and Future<T> interfaces and the Executors class to calculate the sum of numbers from 1 to 5.




PreviousNext

Related