ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Object[] arr = new String[2];
arr[0] = "ok";
try { arr[1] = 42; System.out.print("stored"); }
catch (ArrayStoreException e) { System.out.print("ASE"); }
System.out.print(" " + arr.length);
  1. A. stored 2
  2. B. Compile-time error at arr[1] = 42
  3. C. ASE 2
  4. D. A ClassCastException is thrown

Correct answer: C. ASE 2

Arrays are covariant, so String[] can be referenced as Object[] and arr[1] = 42 compiles; at run time the array knows it is a String[] and throws ArrayStoreException.

More OOP with C++ and Java questions

Exams that ask this topic