ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
Map<String, Integer> m = new HashMap<>();
System.out.print(m.put("a", 1));
System.out.print(" " + m.put("a", 2));
System.out.print(" " + m.size());
  1. A. 1 2 2
  2. B. null 1 1
  3. C. null 1 2
  4. D. 0 1 1

Correct answer: B. null 1 1

put returns the previous value for the key, or null if there was none. The second put replaces 1 with 2 and returns 1. The key is the same, so the size stays 1.

More OOP with C++ and Java questions

Exams that ask this topic