Java OCA OCP Practice Question 2857

Question

Given the proper import(s), and given:

4.   public static void main(String[] args) {  
5.     List<Integer> x = new ArrayList<Integer>();  
6.     x.add(new Integer(3));    
7.     doShape(x);  /*ww w  .  jav  a 2s .  c o m*/
8.     for(Integer i: x)   
9.       System.out.print(i + " ");  
10.   }  
11.   static void doShape(List y) {  
12.     y.add(new Integer(4));  
13.     y.add(new Float(3.14f));  
14.   } 

What is the result? (Choose all that apply.)

  • A. Compilation fails.
  • B. The output will be "4 "
  • C. The output will be "3 4 "
  • D. The output will be "3 4 3.14 "
  • E. The output will be "3 3.14 4 "
  • F. The output will be "3 4 ", followed by an exception.
  • G. An exception will be thrown before any output is produced.


F   is correct.

Note

The doShape() method doesn't know that "y" is a generic collection, so it allows the Float to be added at compile time.

Once doShape() completes, the for loop will succeed until it encounters the Float, at which point a ClassCastException will be thrown.




PreviousNext

Related