Java OCA OCP Practice Question 3137

Question

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

public class Main {
  public static <E> E[] copy(E[] srcArray) {
    E[] destArray = (E[]) new Object[srcArray.length];
    int i = 0;//from  ww  w .  ja v  a2s  .c o  m
    for (E element : srcArray) {
      destArray[i++] = element;
    }
    return destArray;
  }

  public static void main(String[] args) {
    String[] sa = {"9", "1", "1" };
    String[] da = Main.copy(sa);
    System.out.println(da[0]);
  }
}

Select the one correct answer.

  • (a) The program will not compile.
  • (b) The program will compile, but issue an unchecked warning. When run, it will print "9".
  • (c) The program will compile, but issue an unchecked warning. When run, it will throw an exception.
  • (d) The program will compile without any unchecked warnings. When run, it will print "9".
  • (e) The program will compile without any unchecked warnings. When run, it will throw an exception.


(c)

Note

Erasure of E[] in the method copy() is Object[].

The array type Object[] is actually cast to Object[] at runtime, i.e., an identity cast.

The method copy() returns an array of Object.

In the main() method, the assignment of this array to an array of Strings results in a ClassCastException.




PreviousNext

Related