Learn whether HashMap and ConcurrentHashMap in Java allow null keys or values. Understand why, with examples and best practices for safe coding.
🌟 Introduction
Imagine you’re organizing files in labeled folders. But what if one folder doesn’t have a label at all — it’s just blank? Can you still keep it in your cabinet and find it later?
That’s the same question developers ask about Java’s HashMap and ConcurrentHashMap — can you use a null key?
Understanding how these two popular classes handle null keys and null values is crucial for writing robust and bug-free Java programs. It’s a small detail that often leads to NullPointerExceptions or confusing behavior if misunderstood.
In this post, we’ll demystify how HashMap and ConcurrentHashMap treat nul…
Learn whether HashMap and ConcurrentHashMap in Java allow null keys or values. Understand why, with examples and best practices for safe coding.
🌟 Introduction
Imagine you’re organizing files in labeled folders. But what if one folder doesn’t have a label at all — it’s just blank? Can you still keep it in your cabinet and find it later?
That’s the same question developers ask about Java’s HashMap and ConcurrentHashMap — can you use a null key?
Understanding how these two popular classes handle null keys and null values is crucial for writing robust and bug-free Java programs. It’s a small detail that often leads to NullPointerExceptions or confusing behavior if misunderstood.
In this post, we’ll demystify how HashMap and ConcurrentHashMap treat null keys and values, why they differ, and how you should handle them in real-world Java programming.
⚙️ Core Concepts
🧱 HashMap — Yes, It Allows a Null Key
A HashMap in Java can have one null key and multiple null values.
Here’s why:
- When you use
nullas a key,HashMaptreats it as a special case. - Normally, a key’s position is determined using its
hashCode(). But sincenullhas nohashCode()method, HashMap skips that and assigns it to a default bucket (usually index 0 internally).
So, when you call map.put(null, "value"), the HashMap simply stores the entry in that special bucket.
👉 Key takeaway: HashMap is flexible and can handle one null key without issues.
🚫 ConcurrentHashMap — No Null Keys or Values Allowed
Now, let’s talk about ConcurrentHashMap.
Unlike HashMap, ConcurrentHashMap does not allow null keys or null values — and there’s a good reason.
ConcurrentHashMap is designed for multi-threaded environments, where multiple threads read and modify data simultaneously.
If nulls were allowed:
When calling map.get(key) and getting null, you wouldn’t know whether:
- The key doesn’t exist, or
- The key exists but maps to a
nullvalue.
This ambiguity could cause race conditions and make debugging a nightmare in concurrent programs.
Therefore, Java designers made a clear decision — no null keys or values in ConcurrentHashMap to ensure thread safety and data consistency.
⚖️ Summary Table
| Feature | HashMap | ConcurrentHashMap |
|---|---|---|
| Null Key | ✅ Allowed (only one) | ❌ Not Allowed |
| Null Value | ✅ Allowed (multiple) | ❌ Not Allowed |
| Thread Safety | ❌ Not thread-safe | ✅ Thread-safe |
| Performance | Fast (single-threaded) | Optimized for multi-threaded access |
💻 Code Examples (Java 21)
Example 1: HashMap with Null Key and Null Value
import java.util.HashMap;
public class HashMapNullExample {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
// Adding entries, including a null key and null value
map.put(null, "First Value");
map.put("A", "Apple");
map.put("B", null);
// Updating the value of the null key
map.put(null, "Updated Value");
System.out.println("HashMap Contents: " + map);
// Retrieving values
System.out.println("Value for null key: " + map.get(null)); // Updated Value
System.out.println("Value for 'B': " + map.get("B")); // null
}
}
📝 Output:
HashMap Contents: {null=Updated Value, A=Apple, B=null}
Value for null key: Updated Value
Value for 'B': null
✅ Explanation:
- The
nullkey is treated as a special entry. - HashMap can store multiple
nullvalues, but only one null key. - The second
put(null, "Updated Value")overwrites the earlier value.
Example 2: ConcurrentHashMap with Null Key (Throws Exception)
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapNullExample {
public static void main(String[] args) {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
try {
map.put(null, "Value"); // This line will throw an exception
} catch (NullPointerException e) {
System.out.println("Exception: ConcurrentHashMap does not allow null keys!");
}
try {
map.put("A", null); // This will also throw an exception
} catch (NullPointerException e) {
System.out.println("Exception: ConcurrentHashMap does not allow null values!");
}
}
}
📝 Output:
Exception: ConcurrentHashMap does not allow null keys!
Exception: ConcurrentHashMap does not allow null values!
✅ Explanation:
ConcurrentHashMap throws a NullPointerException immediately if you try to insert null as a key or value. This protects your code from thread-safety issues.
🧠 Best Practices
Avoid Using Null Keys Altogether
Even though HashMap allows null keys, using them often causes confusion or bugs. Prefer explicit keys like "UNKNOWN" or "DEFAULT_KEY" instead.
1.
Handle Nulls Gracefully with Optional
Use Optional.ofNullable() to avoid storing nulls in maps:
map.put("Key", Optional.ofNullable(value).orElse("Default"));
For Multi-Threaded Code → Use ConcurrentHashMap
Never use HashMap in concurrent applications; it can lead to inconsistent or corrupted data structures.
1.
Use Defensive Checks Before Insertions Always validate inputs before inserting:
if (key != null && value != null) {
concurrentMap.put(key, value);
}
- Document Your Map Usage Clearly Make it explicit in your code comments or API that nulls are (or aren’t) allowed — especially when designing libraries.
🏁 Conclusion
So, can a HashMap have a null key? 👉 Absolutely — it can hold one null key and multiple null values.
Can a ConcurrentHashMap have a null key? 🚫 No — neither null keys nor null values are allowed, for very good thread-safety reasons.
In single-threaded programs, using HashMap with null keys might seem harmless. But in multi-threaded environments, ConcurrentHashMap’s strict rules protect your application from subtle, hard-to-detect bugs.
Understanding these differences helps you write cleaner, safer, and more efficient Java code — whether you’re building a small utility or a large-scale enterprise system.