Java Interview Preparation
1. How does HashMap work internally?
Answer:
HashMap in Java stores key-value pairs using a hash table. It calculates the hash of the key and places the value in the
corresponding bucket index. If two keys have the same hash, a linked list or tree (Java 8+) is used.
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
System.out.println(map.get("key1"));
Real-life Example:
Like a school locker system: Each student has a locker (bucket) based on an ID (hash).
2. Encapsulation with real time explanation
Answer:
Encapsulation hides internal object details and exposes only necessary parts via public methods. Variables are kept
private and accessed via getters/setters.
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Real-life Example:
ATM: Users only see interface (screen/buttons), not the internal wiring or logic.