ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> h = new HashMap<>();
h.put(null, 1); h.put(null, 2);
System.out.print(h.size() + " " + h.get(null) + " ");
Map<String, Integer> t = new TreeMap<>();
t.put(null, 1);
System.out.print(t.size());
  1. A. 1 2 1
  2. B. 2 2 1
  3. C. Compile-time error at t.put(null, 1)
  4. D. 1 2 is printed, then a NullPointerException is thrown

Correct answer: D. 1 2 is printed, then a NullPointerException is thrown

HashMap permits one null key, so the second put just replaces its value. A TreeMap with natural ordering must compare keys and throws NullPointerException for a null key; the code compiles fine.

More OOP with C++ and Java questions

Exams that ask this topic