ProgrammingHardProduct-company placement · Java

Which line fails to compile?

Which line fails to compile?
List<?> l = new ArrayList<String>();
l.add(null);                                   // L1
l.add("x");                                    // L2
Object o = l.isEmpty() ? null : l.get(0);      // L3
  1. A. L1 and L2
  2. B. L2 and L3
  3. C. None
  4. D. L2 only

Correct answer: D. L2 only

List<?> means 'a list of some unknown type': the only value known to fit is null. Reading elements as Object is always safe.

More OOP with C++ and Java questions

Exams that ask this topic