Java OCA OCP Practice Question 3155

Question

What will be the result of attempting to compile and run the following program?

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.TreeSet;
public class Main {

 public static void main(String[] args) {
   HashSet<Integer> set1 = new HashSet<Integer>();
   addRange(set1, 1);//from  ww  w. ja  va  2s  . co m
   ArrayList<Integer> list1 = new ArrayList<Integer>();
   addRange(list1, 2);
   TreeSet<Integer> set2 = new TreeSet<Integer>();
   addRange(set2, 3);
   LinkedList<Integer> list2 = new LinkedList<Integer>();
   addRange(list2, 5);
   set1.removeAll(list1);
   list1.addAll(set2);
   list2.addAll(list1);
   set1.removeAll(list2);
   System.out.println(set1);
 }
 static void addRange(Collection<Integer> col, int step) {
   for (int i = step*2; i<=25; i+=step)
     col.add(i);
 }
}

Select the one correct answer.

  • (a) The program will fail to compile, since operations are performed on incompatible collection implementations.
  • (b) The program will fail to compile, since the TreeSet referenced by set2 has not been given a Comparator to use when sorting its elements.
  • (c) The program will compile without error, but will throw an UnsupportedOperationException, when run.
  • (d) The program will compile without error and will print all primes below 25, when run.


(d)

Note

The program will compile without error, and will print all primes below 25 when run.

All the collection implementations used in the program implement the Collection interface.

The implementation instances are interchangeable when denoted by Collection references.

None of the operations performed on the implementations will throw an UnsupportedOperationException.

The program finds the primes below 25 by removing all values divisible by 2, 3, and 5 from the set of values from 2 through 25.




PreviousNext

Related