ProgrammingHardProduct-company placement · Java

Which lines fail to compile?

Which lines fail to compile?
List<Integer> ints = new ArrayList<>();
List<Number> nums = ints;              // L1
List<? extends Number> ext = ints;     // L2
ext.add(5);                            // L3
Number n = ext.isEmpty() ? null : ext.get(0);  // L4
  1. A. L1 and L3
  2. B. L1 only
  3. C. L3 only
  4. D. L1, L3 and L4

Correct answer: A. L1 and L3

Generics are invariant: List<Integer> is not a List<Number> (L1). With ? extends Number the compiler does not know the element type, so nothing but null can be added (L3), while reading as Number is fine.

More OOP with C++ and Java questions

Exams that ask this topic