# Java Interview Questions with Answers

12 Java interview questions, each with a model answer, the points to cover, common mistakes and the follow-ups interviewers ask.

_Source: Astra (https://useastra.in). Updated 2026-09-05._

### 1. What is the difference between JDK, JRE, and JVM?

Think of it like a car factory.
**JVM (Engine):** This runs the code. It is the engine inside the car.
**JRE (Car):** This is the engine plus the body and wheels. It lets you *drive* the car (run the program).
**JDK (Factory):** This is the factory. It has the tools to *build* the car (compiler), fix the car (debugger), and drive the car (JRE).

To just run Java, you need JRE. To write Java, you need JDK.

**Points a strong answer covers:**

- JVM executes bytecode; JRE = JVM + libraries; JDK = JRE + dev tools
- Write once run anywhere via JVM abstraction
- JDK for building, JRE for running

**Common mistakes:**

- Three acronyms, no relationship

**Likely follow-ups:**

- Is the JVM Java-only (Kotlin, Scala)?

**What the interviewer is assessing:**

- Platform-model baseline.

### 2. Explain `public static void main` method.

This is the front door of your program.
* **public:** Anyone can enter (the computer needs to find it).
* **static:** It exists even before you build the house (no object needed).
* **void:** It doesn't give anything back when it finishes.
* **main:** The specific name on the doorplate.
* **String args[]:** A mailbox for any messages you send when starting the program.

**Points a strong answer covers:**

- public: JVM must reach it; static: no instance yet; void: no return
- main(String[] args): entry contract
- Exact signature required

**Common mistakes:**

- Memorized words, no reasons

**Likely follow-ups:**

- Why static specifically?

**What the interviewer is assessing:**

- Fundamentals-with-reasons check.

### 3. What are the 4 pillars of OOP?

**1. Encapsulation (Protection):** Like a capsule. You hide the medicine inside. You protect your data with `private` and only let people touch it safely.
**2. Inheritance (Family):** A child gets traits from parents. A `Dog` class gets code from `Animal` class.
**3. Polymorphism (Many Forms):** One button, different actions. Pressing "Play" on a CD player is different from pressing "Play" on a DVD player, but the button looks the same.
**4. Abstraction (Hiding Details):** Driving a car. You use the wheel and pedals. You don't need to know how the engine combustion works.

**Points a strong answer covers:**

- Encapsulation, Inheritance, Polymorphism, Abstraction
- Each with example: private fields, extends, method dispatch, interfaces
- OOP = managing complexity, not vocabulary

**Common mistakes:**

- Listing four words without examples

**Likely follow-ups:**

- Which pillar does composition-over-inheritance challenge?

**What the interviewer is assessing:**

- OOP-literacy screen.

### 4. Difference between `==` and `.equals()`?

**`==` (Address Check):** Checks if two things are the *exact same physical object*. Imagine two identical twin brothers. `==` checks "Is this the exact same person?".
**`.equals()` (Content Check):** Checks if two things *look* the same. `equals()` checks "Do they look exactly alike?".

Always use `.equals()` for Strings and Objects.

**Points a strong answer covers:**

- ==: reference identity (same object)
- equals(): logical equality (if overridden)
- String comparison must use equals; integer cache traps

**Common mistakes:**

- == on strings working "sometimes" unexplained

**Likely follow-ups:**

- Why does 127==127 work but 128==128 fail for Integer?

**What the interviewer is assessing:**

- Identity-vs-equality precision -- classic Java trap.

### 5. Why is String immutable (unchangeable)?

**1. Safety:** Strings are used for passwords and file paths. If they could change, a hacker could sneak in and change a filename after you checked it.
**2. Space:** Java saves space by reusing Strings. If you write "Hello" in 5 places, Java only keeps one copy in memory. If one person changed it, everyone else's "Hello" would break.
**3. Speed:** Since it never changes, Java can memorize (cache) its "fingerprint" (hashcode) so looking it up is super fast.

**Points a strong answer covers:**

- Immutable: security (class loading, params), thread safety, string pool sharing
- hashCode caching for map keys
- New string per modification -- hence builders

**Common mistakes:**

- "It just is" answers

**Likely follow-ups:**

- How does the string pool rely on immutability?

**What the interviewer is assessing:**

- Design-rationale depth.

### 6. What are Wrapper Classes?

Java has two types of data:
1. **Primitives (Simple):** `int`, `char`. Fast but dumb.
2. **Objects (Smart):** `Integer`, `Character`. Slow but powerful.

Lists like `ArrayList` only accept Smart Objects. Wrapper classes are simply the "Smart" version of the "Simple" data types so you can put numbers in a List.
* `int` -> `Integer`
* `char` -> `Character`

**Points a strong answer covers:**

- Objects wrapping primitives (Integer, Double)
- Enable primitives in collections/generics
- Autoboxing converts silently -- perf + null traps

**Common mistakes:**

- No autoboxing-cost awareness

**Likely follow-ups:**

- NullPointerException from unboxing -- example?

**What the interviewer is assessing:**

- Type-system detail.

### 7. What is the `final` keyword?

It means "Cannot Change".
* **Final Variable:** Like writing in permanent marker. Once you write it, you can't erase or change it.
* **Final Method:** "My rules are final." A child class cannot change (override) this method.
* **Final Class:** "No kids allowed." You cannot create a child class from this class (like the `String` class).

**Points a strong answer covers:**

- final variable: no reassignment
- final method: no override; final class: no extension
- Enables immutability + safe publication

**Common mistakes:**

- final = constant oversimplification

**Likely follow-ups:**

- final field with mutable object -- immutable?

**What the interviewer is assessing:**

- Keyword-semantics precision.

### 8. StringBuffer vs StringBuilder?

Both help you change text without wasting memory.
* **StringBuffer:** Think of it like a public notebook where only one person can write at a time. It is safe (thread-safe) but slow because everyone waits in line.
* **StringBuilder:** Like a whiteboard where everyone writes at once. It is fast, but if two people write in the same spot, it gets messy.
**Rule:** Use `StringBuilder` 99% of the time because it is faster.

**Points a strong answer covers:**

- Both mutable strings; StringBuffer synchronized, StringBuilder not
- StringBuilder default choice (faster)
- Buffer only for shared-across-threads mutation (rare)

**Common mistakes:**

- Cannot say when Buffer is right

**Likely follow-ups:**

- Why is + in a loop O(n²)?

**What the interviewer is assessing:**

- API-choice reasoning.

### 9. What is the `static` keyword?

**Static** means "Shared by Everyone".
* **Instance Variable:** Every person has their *own* name.
* **Static Variable:** Everyone in the room shares the *same* air conditioner temperature. If one person changes it, it changes for everyone.
Use `static` for things that should be the same for all objects, like a counter or a constant.

**Points a strong answer covers:**

- static = class-level, shared across instances
- Static methods: no this, no instance state
- Static blocks, nested classes; statics complicate testing

**Common mistakes:**

- Statics everywhere convenience habit

**Likely follow-ups:**

- Why are static methods hard to mock?

**What the interviewer is assessing:**

- Design-consequence awareness.

### 10. Overloading vs Overriding?

**Overloading (Same Name, Different Options):**
Like ordering coffee.
* `order()` -> Regular coffee.
* `order(sugar)` -> Sweet coffee.
* `order(milk, sugar)` -> White coffee.
Same action name, different ingredients.

**Overriding (New Behavior):**
Parent says "Go to sleep at 9 PM".
Child says "I will go to sleep at 11 PM".
The child *replaces* the parent's rule with their own version.

**Points a strong answer covers:**

- Overloading: same name, different params, compile-time
- Overriding: subclass redefines, runtime dispatch
- @Override catches mistakes

**Common mistakes:**

- Compile-vs-runtime dispatch confusion

**Likely follow-ups:**

- Can you override a static method?

**What the interviewer is assessing:**

- Polymorphism-mechanics check.

### 11. What is the Collections Framework?

It is a toolbox of containers to store data.
**List:** Like a grocery list. Order matters. Duplicates allowed. (`ArrayList`)
**Set:** Like a bag of marbles. Order doesn't matter. No duplicates allowed. (`HashSet`)
**Map:** Like a dictionary. You look up a word (Key) to find meaning (Value). (`HashMap`)

**Points a strong answer covers:**

- List/Set/Map/Queue hierarchy + implementations
- ArrayList, HashMap, HashSet everyday trio
- Choose by access pattern + ordering needs

**Common mistakes:**

- Only ever using ArrayList/HashMap unreflectively

**Likely follow-ups:**

- When LinkedHashMap over HashMap?

**What the interviewer is assessing:**

- Data-structure-choice fluency.

### 12. What is an Interface?

An Interface is a **Contract** or a **Menu**.
It lists *what* options are available (e.g., "Grill", "Fry"), but it doesn't do the cooking.
Any class that signs the contract (implements interface) *must* do the work.
Example: `RemoteControl` interface has a button `powerOn()`. The `TV` class provides the code to actually turn on.

**Points a strong answer covers:**

- Contract of methods without implementation
- default/static methods since Java 8
- Program to interfaces; multiple implementation

**Common mistakes:**

- Pre-Java-8 answer in a modern shop

**Likely follow-ups:**

- Why "program to interface, not implementation"?

**What the interviewer is assessing:**

- Abstraction-tool fluency.

Full topic: https://useastra.in/interview-questions/topic/java
