Java HashMap — Java Technical Interview Questions & Answers
Java HashMap
Java HashMap
- HashMap stores key → value, like a register: name → marks. You don’t scan the whole list to find Asha. You ask get("Asha"). Average lookup is very fast. Keys should be unique. Put the same key again and the old value is replaced.
- Let’s take this on the board. HashMap<String, Integer> marks = new HashMap<>(); marks.put("Asha", 90); marks.put("Ravi", 70); print marks.get("Asha"); print marks.get("Neha");. Output: 90 then null. Neha was never put, so get returns null — not an exception. That null surprise fails viva if you don’t mention it.
- Classic HashMap allows one null key and many null values. It is not synchronized. Hashtable is the old synchronized cousin — don’t pick Hashtable unless they ask. String keys are safe. If you use your own class as a key, hashCode and equals must be correct or lookup breaks.
- Iterate with for (var e : marks.entrySet()) and print e.getKey() + "=" + e.getValue(). Don’t only memorise put/get. In a project, HashMap is the default map. Need insertion order? LinkedHashMap. Need sorted keys? TreeMap.
put("Asha", 90)
get("Asha") → 90
get("Neha") → nullTechnical Interview Tip: Say: key → value, put/get, average O(1). Then contrast Hashtable (synced, old) if asked.
Code Examples for Java HashMap
Example
import java.util.HashMap;
// HashMap demo
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Asha", 90);
marks.put("Ravi", 85);
System.out.println(marks.get("Asha"));
}
}Java HashMap — output: 90. HashMap stores Asha→90, Ravi→85. get("Asha") looks up the key.
How to Explain Java HashMap to an Interviewer
What does HashMap store?
key → value
How do you add and read?
put get
Is HashMap synchronized?
No