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

Java Interview Preparation Sample (2)

The document provides Java interview questions focused on HashMap and encapsulation, explaining their internal workings and real-life analogies. HashMap uses arrays and linked lists (or trees) to store key-value pairs, similar to a student locker system. Encapsulation is illustrated through a bank ATM example, highlighting the restriction of direct access to an object's components while allowing safe usage of its features.

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)
3 views1 page

Java Interview Preparation Sample (2)

The document provides Java interview questions focused on HashMap and encapsulation, explaining their internal workings and real-life analogies. HashMap uses arrays and linked lists (or trees) to store key-value pairs, similar to a student locker system. Encapsulation is illustrated through a bank ATM example, highlighting the restriction of direct access to an object's components while allowing safe usage of its features.

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 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.

You might also like