Java OCA OCP Practice Question 2537

Question

Consider the following program and predict the output:

import java.util.*;

public class Main {
     public static void main(String []args) {
        List<Integer> intList = new ArrayList<>();
        intList.add(10);/*from   ww  w  .ja  v a  2  s.  c om*/
        intList.add(20);
        List list = intList;
        list.add("hello");              // ADD_STR
        for(Object o : list) {
           System.out.print(o + " ");
        }
     }
}
  • a) This program will not print any output and will throw ClassCastException.
  • b) This program will first print 10 and 20 and then throw ClassCastException.
  • c) This program will result in a compiler error in line marked with comment ADD_STR.
  • d) This program will print 10, 20, and hello.


d)

Note

The raw type List gets initialized from List<Integer> (which generates a compiler warning not an error), and then you add a string element to the raw List, which is allowed.

Then the whole list gets iterated to print each element; each element gets cast to the Object type, so it prints 10, 20, and hello.




PreviousNext

Related