ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, String> h = new HashMap<>();
h.put("k", null);
System.out.print(h.size() + " ");
Map<String, String> c = new ConcurrentHashMap<>();
c.put("k", null);
System.out.print(c.size());
  1. A. 1 1
  2. B. 0 0
  3. C. "1 " is printed, then a NullPointerException is thrown
  4. D. 1 0

Correct answer: C. "1 " is printed, then a NullPointerException is thrown

HashMap allows null keys and values. ConcurrentHashMap forbids both, because get() returning null must unambiguously mean 'absent' under concurrency.

More OOP with C++ and Java questions

Exams that ask this topic