Java OCA OCP Practice Question 2306

Question

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

public class Main {
  public static void main(String[] args) {
    List<Integer> lst = new ArrayList<Integer>();  // (1)
    lst.add(2007);//from  www  . j  a  v a 2  s.  c  o m
    lst.add(2008);
    List<Number> numList = lst;                    // (2)
    for(Number n : numList)                        // (3)
      System.out.println(n + " ");
  }
}

Select the one correct answer.

  • (a) The code will fail to compile because of an error in (1).
  • (b) The code will fail to compile because of an error in (2).
  • (c) The code will fail to compile because of an error in (3).
  • (d) The code will compile, but throw a ClassCastException at runtime in (2).
  • (e) The code will compile and will print "2007 2008 ", when run.


(b)

Note

The type of lst is List of Integer and the type of numList is List of Number.

The compiler issues an error because List<Integer> is not a subtype of List<Number>.




PreviousNext

Related