Java Interview Preparation
1. How hash map will internally work?
Answer:
A HashMap in Java stores key-value pairs using an array of buckets. Each key?s `hashCode()` determines the bucket
index. If two keys have the same hash, a linked list is used to handle collisions (Java 7), or a balanced tree (Java 8+) if
collisions exceed a threshold. Insert and lookup operations generally perform in O(1) time on average.
import java.util.HashMap;
public class Q1Demo {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("name", "John");
map.put("role", "Developer");
System.out.println(map.get("name")); // Output: John
}
}
Real-life Example:
Think of a school locker system. Each student has a unique ID (key), and the locker (bucket) stores their books (value).
If two students get the same locker number by accident (hash collision), they share the locker using compartments
(linked list or tree).
2. Encapsulation with real time explanation
Answer:
Encapsulation is the concept of wrapping data (variables) and behavior (methods) together in a single unit (class). It
hides the internal state of an object from the outside world using private fields and provides access via public
getters/setters.
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Real-life Example:
Think of a coffee vending machine. You press a button (public method), but you don?t see the internal mechanism
(private data/logic). You get the coffee, but not how it was made ? that's encapsulation.