ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<>();
        m.put(new String("key"), 1);
        m.put("key", 2);
        System.out.println(m.size() + " " + m.get("key"));
    }
}
  1. A. 2 1
  2. B. 1 2
  3. C. 2 2
  4. D. 1 1

Correct answer: B. 1 2

String correctly overrides both equals() and hashCode() based on content, so new String("key") and the literal "key" are treated as the same key by HashMap despite being different objects. The second put() overwrites the first entry's value, leaving size 1 and the stored value 2.

More OOP with C++ and Java questions

Exams that ask this topic