ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
int x = m.getOrDefault("b", 0) + m.get("a");
int y = m.get("b");
System.out.print(x + y);
  1. A. 1
  2. B. A NullPointerException is thrown; nothing is printed
  3. C. Compile-time error
  4. D. 1null

Correct answer: B. A NullPointerException is thrown; nothing is printed

x is 0 + 1 = 1, but m.get("b") returns null and assigning it to an int auto-unboxes null, which throws NullPointerException before the print.

More OOP with C++ and Java questions

Exams that ask this topic