Java Interview Questions with Code and Real-life Examples
1. How does HashMap work internally?
A HashMap in Java uses a combination of arrays and linked lists (or trees, after Java 8) to store key-value pairs.
Code Example:
```java
Map<String, String> map = new HashMap<>();
map.put("one", "1");
map.put("two", "2");
```
Real-life Example:
Think of a student locker system. Each student has a unique locker number (key), and the locker stores the student's
items (value).
The HashMap uses the hashCode of the key to find the correct bucket to store or retrieve the value.
2. What is encapsulation? Give a real-time example.
Encapsulation is the concept of wrapping data (variables) and methods into a single unit (class), restricting direct access
to some of the object's components.
Code Example:
```java
public class Employee {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
```
Real-life Example:
A bank ATM allows access to your account through your PIN. You don?t get to see how it works internally but can use
its features safely.