ProgrammingHardProduct-company placement · GATE CS

Which statement about this code is correct?

Which statement about this code is correct?
Object[] arr = new String[2];               // L1
arr[0] = "a";                               // L2
arr[1] = Integer.valueOf(1);                // L3
List<Object> list = new ArrayList<String>(); // L4
  1. A. L1 fails to compile because String[] is not an Object[]
  2. B. Everything compiles, and L3 and L4 both fail at run time
  3. C. L4 fails to compile; without L4, the code compiles and L3 throws ArrayStoreException at run time
  4. D. L3 fails to compile because Integer is not a String

Correct answer: C. L4 fails to compile; without L4, the code compiles and L3 throws ArrayStoreException at run time

Arrays are covariant and checked at run time, so L1 and L3 compile but storing an Integer into the real String[] throws ArrayStoreException. Generics are invariant and checked at compile time, so List<String> is not a List<Object>.

More OOP with C++ and Java questions

Exams that ask this topic