0% found this document useful (0 votes)
2 views1 page

Java Prep Sample

The document provides a brief overview of HashMap and encapsulation in Java. It explains that HashMap uses hashCode() for storing key-value pairs and handles collisions with linked lists or balanced trees. Additionally, it illustrates encapsulation with a BankAccount class example, highlighting the use of private fields and public methods for access.

Uploaded by

Jana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Java Prep Sample

The document provides a brief overview of HashMap and encapsulation in Java. It explains that HashMap uses hashCode() for storing key-value pairs and handles collisions with linked lists or balanced trees. Additionally, it illustrates encapsulation with a BankAccount class example, highlighting the use of private fields and public methods for access.

Uploaded by

Jana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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; }
}

You might also like