Yes. A HashMap allows exactly one null key and any number of null values. The null key is treated as having a hash of 0, so it is always stored in bucket 0. TreeMap, Hashtable and ConcurrentHashMap do not allow null keys.
Key Points: • HashMap's hash() method returns 0 for a null key, so it doesn't call hashCode() on null. • Putting a second value with a null key replaces the first, just like any other key. • get(key) returning null is ambiguous: the key might be missing or mapped to null. Use containsKey() to tell the difference. • TreeMap throws NullPointerException for a null key with natural ordering, because it must compare keys. • HashSet allows one null element because it is backed by a HashMap.
Code Example:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class NullKeyDemo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put(null, "first");
map.put(null, "second"); // replaces "first"
map.put("city", null); // null values are fine too
System.out.println(map.get(null));
System.out.println("Size: " + map.size());
System.out.println("get(\"city\") = " + map.get("city")
+ ", containsKey = " + map.containsKey("city"));
System.out.println("get(\"pin\") = " + map.get("pin")
+ ", containsKey = " + map.containsKey("pin"));
try {
new TreeMap<String, String>().put(null, "x");
} catch (NullPointerException e) {
System.out.println("TreeMap: null key rejected");
}
}
}Output:
second Size: 2 get("city") = null, containsKey = true get("pin") = null, containsKey = false TreeMap: null key rejected
Good to Know: Allowing null keys is generally considered a design mistake today, which is why newer maps such as ConcurrentHashMap and Map.of() reject them. In real code, avoid null keys and use Optional or a clear default value instead.
Interview Tip: A concise interview answer is:
"Yes, HashMap allows one null key and many null values. Its hash function treats a null key as hash 0, so it goes into bucket 0, and a second put with null replaces the first value. TreeMap, Hashtable and ConcurrentHashMap don't allow null keys, and because get() returns null for missing keys too, I use containsKey() when the difference matters."
Previous question: How do you avoid ConcurrentModificationException when removing elements from a list?
Next question: What are the initial capacity and load factor of a HashMap, and what happens when it resizes?