Java OCA OCP Practice Question 3131

Question

What will be printed when the program is compiled and run?

public class Main {
  public static void main(String[] args) {
    Object obj = new ArrayList<Integer>();         // (1)
    List<?>       list1 = (List<?>) obj;           // (2)
    List<?>       list2 = (List) obj;              // (3)
    List          list3 = (List<?>) obj;           // (4)
    List<Integer> list4 = (List) obj;              // (5)
    List<Integer> list5 = (List<Integer>) obj;     // (6)
  }/*from w ww  . java  2 s  . co  m*/
}

Select the one correct answer.

  • (a) The program will not compile.
  • (b) The program will compile without any unchecked warnings. It will run with no output and terminate normally.
  • (c) The program will compile without any unchecked warnings. When run, it will throw an exception.
  • (d) The program will compile, but issue unchecked warnings. It will run with no output and terminate normally.
  • (e) The program will compile, but issue unchecked warnings. When run, it will throw an exception.


(d)

Note

Casts are permitted, as in (2)-(6), but can result in an unchecked warning.

The assignment in (5) is from a raw type (List) to a parameterized type (List<Integer>), resulting in an unchecked assignment conversion warning.

Note that in (5) the cast does not pose any problem.

It is the assignment from generic code to legacy code that can be a potential problem, flagged as an unchecked warning.

In (6), the cast is against the erasure of List<Integer>, that is to say, List.

The compiler cannot guarantee that obj is a List<Integer> at runtime, it therefore flags the cast with an unchecked warning.




PreviousNext

Related