ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> m = new HashMap<>();
System.out.print(m.putIfAbsent("k", 1) + " ");
System.out.print(m.putIfAbsent("k", 2) + " ");
System.out.print(m.computeIfAbsent("k", s -> 3) + " ");
System.out.print(m.get("k"));
  1. A. 1 2 3 3
  2. B. null 1 1 1
  3. C. null 1 3 3
  4. D. null null 1 1

Correct answer: B. null 1 1 1

putIfAbsent returns the PREVIOUS value (null, then 1) and does not overwrite. computeIfAbsent returns the current value (1) without calling the function because the key is present.

More OOP with C++ and Java questions

Exams that ask this topic