ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

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.putIfAbsent("a", 3));
System.out.print(m.get("a"));
  1. A. null123
  2. B. null122
  3. C. 1223
  4. D. null1null2

Correct answer: B. null122

put returns the previous value: null the first time, then 1. putIfAbsent finds a present key, changes nothing and returns the current value 2, and get returns 2.

More OOP with C++ and Java questions

Exams that ask this topic