ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.keySet().remove("a");
System.out.print(m.size() + " ");
m.keySet().add("b");
  1. A. "0 " is printed, then UnsupportedOperationException is thrown
  2. B. "0 " is printed, then b is added with value null
  3. C. 1 then UnsupportedOperationException
  4. D. Compile-time error: keySet() is read-only

Correct answer: A. "0 " is printed, then UnsupportedOperationException is thrown

keySet() is a live view: removing through it removes the mapping. Adding through it is unsupported, since a key alone does not say what value to store.

More OOP with C++ and Java questions

Exams that ask this topic