ProgrammingHardProduct-company placement · Java

Which lines fail to compile?

Which lines fail to compile?
// Java 10 or later
var list = new ArrayList<>();   // L1
list.add(1); list.add("a");     // L2
var x;                          // L3
var y = null;                   // L4
var z = new int[]{1, 2};        // L5
  1. A. L2, L3 and L4
  2. B. L3 only
  3. C. L3 and L4
  4. D. L1, L3 and L4

Correct answer: C. L3 and L4

var needs an initializer from which a type can be inferred: L3 has none and null (L4) has no usable type. L1 infers ArrayList<Object>, so adding both an Integer and a String is fine.

More OOP with C++ and Java questions

Exams that ask this topic