JAVA PREPARATION - SAMPLE
Q1. How does HashMap work internally?
Answer: HashMap stores key-value pairs in buckets decided by hashCode(). Collisions are
handled by linked list (Java 7) or balanced tree (Java 8+).
Real-time Example: Like a dictionary: word (key) -> meaning (value).
import java.util.*;
public class HashMapDemo {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map.get("Apple"));
}
}
Q2. Encapsulation with real-time explanation
Answer: Encapsulation hides internal fields using private and exposes access via getters/setters.
Real-time Example: ATM: you deposit/withdraw but can’t access bank core system directly.
class BankAccount {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { balance += amt; }
}