Java Basics
What is Java?
Answer:
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now owned by Oracle).
Java follows the principle:
Write Once, Run Anywhere (WORA)
This means Java programs can run on any system that has a JVM, without changing the code.
Interview line:
“Java is platform-independent because it runs on JVM, not directly on the OS.”
Q2. Why is Java platform-independent?
Answer:
Java source code is compiled into bytecode, not machine code.
Flow:
.java → compiler → .class (bytecode) → JVM → OS
The JVM converts bytecode into machine-specific instructions.
Important clarification:
- Java is compiled + interpreted
- Bytecode makes it portable
Q3. What are JDK, JRE, and JVM?
Answer:
| Component | Meaning |
|---|---|
| JVM | Executes bytecode |
| JRE | JVM + core libraries |
| JDK | JRE + development tools |
Relationship:
JDK ⊃ JRE ⊃ JVM
Interview trap:
JVM does NOT contain the compiler — JDK does.
Q4. What are the main features of Java?
Answer:
Key Java features include:
- Platform independent
- Object-oriented
- Secure
- Robust
- Multithreaded
- Automatic memory management
- Rich standard library
Interview line:
“Java focuses on reliability and maintainability.”
Q5. What is Object-Oriented Programming (OOP)?
Answer:
OOP is a programming paradigm based on objects, which combine:
- Data (variables)
- Behavior (methods)
Java is built around OOP principles to make code:
- Modular
- Reusable
- Easy to maintain
Q6. What are the four pillars of OOP?
Answer:
The four pillars are:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Interview tip:
Always explain with simple examples, not definitions.
Q7. What is Encapsulation?
Answer:
Encapsulation means wrapping data and methods together and controlling access.
Achieved using:
- Private variables
- Public getter/setter methods
Example:
class User {
private String name;
public String getName() {
return name;
}
}
Interview line:
“Encapsulation protects data from unauthorized access.”
Q8. What is Inheritance?
Answer:
Inheritance allows one class to acquire properties of another class.
Achieved using:
extends
Example:
class Animal { }
class Dog extends Animal { }
Benefits:
- Code reuse
- Hierarchical relationship
Q9. What is Polymorphism?
Answer:
Polymorphism means one interface, multiple implementations.
Two types:
- Compile-time (method overloading)
- Runtime (method overriding)
Example:
Animal a = new Dog();
a.sound();
Interview line:
“Runtime polymorphism is achieved through method overriding.”
Q10. What is Abstraction?
Answer:
Abstraction means hiding implementation details and showing only essential features to the user.
In Java, abstraction is achieved using:
- Abstract classes
- Interfaces
Simple explanation:
The user knows what the object does, not how it does it.
Example:
interface Vehicle {
void start();
}
You don’t know how the engine starts, you only know it starts.
Q11. Difference between Abstract Class and Interface
Answer:
| Abstract Class | Interface |
| Can have concrete methods | Only abstract methods (before Java 8) |
| Can have instance variables | Only constants |
| Supports constructors | No constructors |
| Supports single inheritance | Supports multiple inheritance |
Interview line:
“Use interfaces for contracts, abstract classes for base functionality.”
Q12. What is the difference between == and .equals()?
Answer:
- == compares references
- .equals() compares content
Example:
String a = new String(“Java”);
String b = new String(“Java”);
a == b // false
a.equals(b) // true
Interview trap:
For primitives, == compares values.
Q13. Why is String immutable in Java?
Answer:
String is immutable because of:
- Security
- Thread safety
- Performance (String pool)
- Caching & hashing
Example:
String s = “Java”;
s.concat(“World”); // creates new object
Interview gold line:
“Immutability makes String secure and thread-safe.”
Q14. What is String Pool?
Answer:
String Pool is a special memory area in heap where String literals are stored.
String s1 = “Java”;
String s2 = “Java”;
Both point to the same object in the pool.
Benefit:
- Saves memory
- Improves performance
Q15. Difference between String, StringBuilder, and StringBuffer
Answer:
| Feature | String | StringBuilder | StringBuffer |
| Mutable | ❌ No | ✅ Yes | ✅ Yes |
| Thread-safe | Yes | No | Yes |
| Performance | Slow | Fast | Slower |
Interview rule:
“Use StringBuilder in single-threaded scenarios.”
Q16. What is Constructor?
Answer:
A constructor is a special method used to initialize objects.
Rules:
- Same name as class
- No return type
- Called automatically
Example:
class User {
User() {
System.out.println(“Object created”);
}
}
Q17. What is the difference between Constructor and Method?
Answer:
| Constructor | Method |
| Initializes object | Performs logic |
| No return type | Has return type |
| Called automatically | Called explicitly |
Q18. What is static keyword?
Answer:
static belongs to the class, not the object.
Used for:
- Variables
- Methods
- Blocks
- Nested classes
Example:
static int count;
Interview line:
“Static members are shared across all objects.”
Q19. What is final keyword?
Answer:
final means cannot be changed.
Usage:
- final variable → constant
- final method → cannot override
- final class → cannot inherit
Q20. What is this keyword?
Answer:
this refers to the current object.
Used to:
- Differentiate instance variables
- Call another constructor
- Pass current object
Example:
this.name = name;
Q21. What is super keyword?
Answer:
super refers to the parent class object.
Used to:
- Access parent variables
- Call parent constructor
- Invoke parent methods
Q22. What is Method Overloading?
Answer:
Method overloading means:
- Same method name
- Different parameters
- Same class
add(int a, int b)
add(double a, double b)
Interview line:
“Overloading happens at compile time.”
Q23. What is Method Overriding?
Answer:
Method overriding means:
- Same method signature
- Parent–child relationship
- Runtime polymorphism
class Dog extends Animal {
void sound() { }
}
Q24. What is public static void main(String[] args)?
Answer:
It is the entry point of Java application.
Breakdown:
- public → JVM can access
- static → no object required
- void → no return
- String[] args → command-line arguments
Q25. What is Exception?
Answer:
An exception is an abnormal event that disrupts program flow.
Types:
- Checked exceptions
- Unchecked exceptions
Example:
NullPointerException
IOException
Q26. Difference between Checked and Unchecked Exception
Answer:
| Checked | Unchecked |
| Compile-time | Runtime |
| Must handle | Optional |
| Example: IOException | Example: NullPointerException |
Q27. What is try-catch-finally?
Answer:
Used to handle exceptions.
try {
// risky code
} catch(Exception e) {
// handle
} finally {
// always executes
}
Q28. What is throw vs throws?
Answer:
- throw → explicitly throw exception
- throws → declare exception
Q29. What is Garbage Collection?
Answer:
Garbage Collection automatically removes unused objects from memory.
Benefits:
- Prevents memory leaks
- No manual memory management
Interview line:
“GC improves productivity, not performance.”
Q30. What is JVM Memory Structure?
Answer:
JVM memory areas:
Native method stack
Heap
Stack
Method area
PC register
🧩 Category 2: Object-Oriented Programming (OOP)
What is Object-Oriented Programming (OOP)?
Answer :
Object-Oriented Programming is a programming paradigm that organizes code around objects, not functions.
An object represents:
- State → variables
- Behavior → methods
OOP helps in building:
- Modular code
- Reusable components
- Maintainable systems
Interview line:
“OOP models real-world entities as software objects.”
Q2. Why is Java called an Object-Oriented language?
Answer:
Java is considered object-oriented because:
- Everything revolves around classes and objects
- Code is organized using OOP principles
- Even primitive usage is wrapped via objects (Wrapper classes)
Important clarification:
Java is not 100% object-oriented because:
- It supports primitive data types (int, char, etc.)
🟦 THE FOUR PILLARS (VERY IMPORTANT)
Q3. Explain Encapsulation in detail
Answer:
Encapsulation is the practice of:
- Hiding internal data
- Exposing controlled access
Achieved using:
- private variables
- public getters and setters
Example:
class Account {
private double balance;
public double getBalance() {
return balance;
}
}
Why it matters:
- Prevents accidental modification
- Improves security
- Makes code maintainable
Interview gold line:
“Encapsulation protects data integrity.”
Q4. What is Inheritance and why is it used?
Answer:
Inheritance allows a class to reuse properties and behavior of another class.
class Vehicle { }
class Car extends Vehicle { }
Benefits:
- Code reuse
- Logical hierarchy
- Easier maintenance
Interview warning:
Java supports single inheritance for classes to avoid ambiguity.
Q5. Why does Java not support multiple inheritance with classes?
Answer:
Java avoids multiple inheritance with classes to prevent the Diamond Problem.
Diamond Problem:
Two parent classes have same method → child doesn’t know which one to use.
Solution:
Java allows multiple inheritance via interfaces.
Interview line:
“Java avoids multiple inheritance to maintain clarity and simplicity.”
Q6. What is Polymorphism? Explain deeply.
Answer:
Polymorphism means one interface, multiple implementations.
Two types:
1️⃣ Compile-time Polymorphism
- Method overloading
- Resolved at compile time
2️⃣ Runtime Polymorphism
- Method overriding
- Resolved at runtime using dynamic binding
Example:
Animal a = new Dog();
a.sound();
Interview power line:
“Runtime polymorphism enables loose coupling.”
Q7. What is Abstraction and why is it needed?
Answer:
Abstraction focuses on what an object does, not how it does it.
Achieved using:
- Abstract classes
- Interfaces
Real-world analogy:
You drive a car without knowing engine internals.
Interview line:
“Abstraction reduces complexity and improves design.”
🟦 ABSTRACT CLASS VS INTERFACE (VERY COMMON)
Q8. Difference between Abstract Class and Interface (Deep)
Answer:
| Abstract Class | Interface |
| Can have state | No state (constants only) |
| Supports constructors | No constructors |
| Partial abstraction | Full abstraction |
| Single inheritance | Multiple inheritance |
When to use:
- Abstract class → “is-a” relationship with shared code
- Interface → contract / capability
Q9. What changed in Interfaces after Java 8?
Answer:
Java 8 introduced:
- default methods
- static methods
This allows:
- Backward compatibility
- Evolution of interfaces
Interview line:
“Default methods allow interfaces to evolve without breaking implementations.”
🟦 OBJECT CREATION & BEHAVIOR
Q10. What is Dynamic Binding?
Answer:
Dynamic binding means:
- Method call is resolved at runtime
- Based on actual object type
Used in:
- Method overriding
- Runtime polymorphism
Q11. What is instanceof and when should you use it?
Answer:
instanceof checks object type at runtime.
if (obj instanceof Dog) { }
Interview caution:
Overuse of instanceof indicates poor design.
Q12. What is Object class in Java?
Answer:
Object is the root class of all Java classes.
Common methods:
- toString()
- equals()
- hashCode()
- clone()
Every class implicitly extends Object.
Q13. Why must equals() and hashCode() be overridden together?
Answer:
Contract:
- Equal objects must have same hash code
- Hash-based collections depend on this
Interview gold line:
“Breaking equals-hashCode contract breaks collections.”
🟦 DESIGN & INTERVIEW SCENARIOS
Q14. Is composition better than inheritance?
Answer:
Yes, in many cases.
Inheritance:
- Tight coupling
- Fragile hierarchy
Composition:
- Loose coupling
- More flexible design
Interview line:
“Favor composition over inheritance.”
Q15. Can we override static methods?
Answer:
No.
Static methods belong to the class, not object.
This is called method hiding, not overriding.
Q16. Can we override private methods?
Answer:
No.
Private methods are not visible to subclasses.
Q17. Can constructor be overridden?
Answer:
No.
Constructors are not inherited.
Q18. What is the difference between IS-A and HAS-A relationship?
Answer:
- IS-A → Inheritance
- HAS-A → Composition
Example:
- Car IS-A Vehicle
- Car HAS-A Engine
📚 Category 3: Collections & Generics
What is Object-Oriented Programming (OOP)?
Answer:
Object-Oriented Programming is a programming paradigm that organizes code around objects, not functions.
An object represents:
- State → variables
- Behavior → methods
OOP helps in building:
- Modular code
- Reusable components
- Maintainable systems
Interview line:
“OOP models real-world entities as software objects.”
Q2. Why is Java called an Object-Oriented language?
Answer:
Java is considered object-oriented because:
- Everything revolves around classes and objects
- Code is organized using OOP principles
- Even primitive usage is wrapped via objects (Wrapper classes)
Important clarification:
Java is not 100% object-oriented because:
- It supports primitive data types (int, char, etc.)
🟦 THE FOUR PILLARS (VERY IMPORTANT)
Q3. Explain Encapsulation in detail
Answer:
Encapsulation is the practice of:
- Hiding internal data
- Exposing controlled access
Achieved using:
- private variables
- public getters and setters
Example:
class Account {
private double balance;
public double getBalance() {
return balance;
}
}
Why it matters:
- Prevents accidental modification
- Improves security
- Makes code maintainable
Interview gold line:
“Encapsulation protects data integrity.”
Q4. What is Inheritance and why is it used?
Answer:
Inheritance allows a class to reuse properties and behavior of another class.
class Vehicle { }
class Car extends Vehicle { }
Benefits:
- Code reuse
- Logical hierarchy
- Easier maintenance
Interview warning:
Java supports single inheritance for classes to avoid ambiguity.
Q5. Why does Java not support multiple inheritance with classes?
Answer:
Java avoids multiple inheritance with classes to prevent the Diamond Problem.
Diamond Problem:
Two parent classes have same method → child doesn’t know which one to use.
Solution:
Java allows multiple inheritance via interfaces.
Interview line:
“Java avoids multiple inheritance to maintain clarity and simplicity.”
Q6. What is Polymorphism? Explain deeply.
Answer:
Polymorphism means one interface, multiple implementations.
Two types:
1️⃣ Compile-time Polymorphism
- Method overloading
- Resolved at compile time
2️⃣ Runtime Polymorphism
- Method overriding
- Resolved at runtime using dynamic binding
Example:
Animal a = new Dog();
a.sound();
Interview power line:
“Runtime polymorphism enables loose coupling.”
Q7. What is Abstraction and why is it needed?
Answer:
Abstraction focuses on what an object does, not how it does it.
Achieved using:
- Abstract classes
- Interfaces
Real-world analogy:
You drive a car without knowing engine internals.
Interview line:
“Abstraction reduces complexity and improves design.”
🟦 ABSTRACT CLASS VS INTERFACE (VERY COMMON)
Q8. Difference between Abstract Class and Interface (Deep)
Answer:
| Abstract Class | Interface |
| Can have state | No state (constants only) |
| Supports constructors | No constructors |
| Partial abstraction | Full abstraction |
| Single inheritance | Multiple inheritance |
When to use:
- Abstract class → “is-a” relationship with shared code
- Interface → contract / capability
Q9. What changed in Interfaces after Java 8?
Answer:
Java 8 introduced:
- default methods
- static methods
This allows:
- Backward compatibility
- Evolution of interfaces
Interview line:
“Default methods allow interfaces to evolve without breaking implementations.”
🟦 OBJECT CREATION & BEHAVIOR
Q10. What is Dynamic Binding?
Answer:
Dynamic binding means:
- Method call is resolved at runtime
- Based on actual object type
Used in:
- Method overriding
- Runtime polymorphism
Q11. What is instanceof and when should you use it?
Answer:
instanceof checks object type at runtime.
if (obj instanceof Dog) { }
Interview caution:
Overuse of instanceof indicates poor design.
Q12. What is Object class in Java?
Answer:
Object is the root class of all Java classes.
Common methods:
- toString()
- equals()
- hashCode()
- clone()
Every class implicitly extends Object.
Q13. Why must equals() and hashCode() be overridden together?
Answer:
Contract:
- Equal objects must have same hash code
- Hash-based collections depend on this
Interview gold line:
“Breaking equals-hashCode contract breaks collections.”
🟦 DESIGN & INTERVIEW SCENARIOS
Q14. Is composition better than inheritance?
Answer:
Yes, in many cases.
Inheritance:
- Tight coupling
- Fragile hierarchy
Composition:
- Loose coupling
- More flexible design
Interview line:
“Favor composition over inheritance.”
Q15. Can we override static methods?
Answer:
No.
Static methods belong to the class, not object.
This is called method hiding, not overriding.
Q16. Can we override private methods?
Answer:
No.
Private methods are not visible to subclasses.
Q17. Can constructor be overridden?
Answer:
No.
Constructors are not inherited.
Q18. What is the difference between IS-A and HAS-A relationship?
Answer:
- IS-A → Inheritance
- HAS-A → Composition
Example:
- Car IS-A Vehicle
- Car HAS-A Engine
⚙️ Category 4: Advanced Java Concepts
Q7. Explain Garbage Collection in Java.
- Answer: JVM automatically removes unused objects to free memory.
- Phases: Mark → Sweep → Compact.
- Best practice: Avoid calling
System.gc()manually; let JVM manage it.
Q8. What is the difference between throw and throws?
throw: Used to explicitly throw an exception inside a method.throws: Declares exceptions a method might throw.- Example:java
void readFile() throws IOException { throw new IOException("File not found"); } ```
🔒 Category 5: Multithreading & Concurrency
PART 1: THREAD LIFECYCLE & BASICS (WITH HANDS-ON)
Q1. Explain Thread Lifecycle with Real Example
Thread States:
- New
- Runnable
- Running
- Blocked / Waiting
- Terminated
Hands-on Example:
Thread t = new Thread(() -> {
System.out.println(“Running”);
});
t.start();
- new → before start
- runnable → after start
- running → CPU executes
- terminated → execution ends
Interview line:
“Thread scheduling is controlled by JVM and OS, not by developer.”
Q2. What happens if start() is called twice?
Answer:
Calling start() twice throws:
IllegalThreadStateException
Why?
A thread can be started only once.
🟦 PART 2: SYNCHRONIZATION (CORE HANDS-ON)
Q3. What is Race Condition?
Scenario:
Two threads update same variable.
class Counter {
int count = 0;
void increment() {
count++;
}
}
Problem:
Multiple threads may update count incorrectly.
Interview line:
“Race condition occurs when multiple threads access shared mutable data without coordination.”
Q4. How does synchronized solve this?
Hands-on:
synchronized void increment() {
count++;
}
What synchronized does:
- Allows only one thread at a time
- Uses intrinsic lock (monitor)
Interview gold:
“Synchronization provides mutual exclusion and visibility.”
Q5. synchronized method vs synchronized block
Example:
synchronized(this) {
// critical section
}
Difference:
- Method → locks entire method
- Block → locks only critical code
Interview preference:
“Synchronized blocks give better performance.”
🟦 PART 3: DEADLOCK (VERY IMPORTANT)
Q6. What is Deadlock?
Scenario:
Thread A holds Lock1, waits for Lock2
Thread B holds Lock2, waits for Lock1
Hands-on Deadlock Example:
synchronized(lock1) {
synchronized(lock2) { }
}
Interview line:
“Deadlock is a design issue, not a JVM bug.”
Q7. How do you prevent Deadlock?
Solutions:
- Lock ordering
- Timeout on locks
- Avoid nested locks
- Use higher-level concurrency APIs
Senior interview line:
“The best deadlock prevention is correct lock design.”
🟦 PART 4: VOLATILE & VISIBILITY
Q8. What problem does volatile solve?
Answer:
volatile ensures:
- Visibility of variable updates
- No CPU cache inconsistency
Example:
volatile boolean running = true;
Important:
❌ Does NOT guarantee atomicity
✅ Guarantees visibility
Interview trap:
Volatile is NOT a replacement for synchronization.
🟦 PART 5: WAIT / NOTIFY (CLASSIC SCENARIO)
Q9. Producer–Consumer using wait/notify
Hands-on Concept:
- Producer produces data
- Consumer waits if data not available
Example:
synchronized(obj) {
obj.wait();
}
synchronized(obj) {
obj.notify();
}
Interview rule:
wait() and notify() must be called inside synchronized block.
Q10. Difference between wait() and sleep()
| wait() | sleep() |
| Releases lock | Does not release lock |
| Object class | Thread class |
| Used in coordination | Used for pause |
🟦 PART 6: JAVA UTIL CONCURRENT (REAL WORLD)
Q11. Why java.util.concurrent is important?
Answer:
Low-level synchronization is:
- Error-prone
- Hard to maintain
java.util.concurrent provides:
- Thread-safe utilities
- Better performance
- Cleaner code
Q12. Executor Framework (VERY IMPORTANT)
Problem with manual threads:
- Hard to manage
- No reuse
- Resource leaks
Solution:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> task());
Interview line:
“Executor decouples task submission from execution.”
Q13. Difference between submit() and execute()
| submit() | execute() |
| Returns Future | No return |
| Handles exceptions | Throws runtime exception |
Q14. What is Thread Pool?
Answer:
Thread pool:
- Reuses threads
- Limits resource usage
- Improves performance
Types:
- Fixed thread pool
- Cached thread pool
- Scheduled thread pool
🟦 PART 7: CONCURRENT COLLECTIONS
Q15. Why ConcurrentHashMap instead of HashMap?
Answer:
HashMap:
- Not thread-safe
- Causes data corruption
ConcurrentHashMap:
- Thread-safe
- High concurrency
- No global locking
Interview gold:
“ConcurrentHashMap achieves thread safety with minimal locking.”
Q16. Fail-Fast vs Fail-Safe Iterators
| Fail-Fast | Fail-Safe |
| Throws exception | No exception |
| Works on original | Works on copy |
| ArrayList | ConcurrentHashMap |
🟦 PART 8: REAL INTERVIEW SCENARIOS (MUST PRACTICE)
Scenario 1: Application is slow under load
How do you debug?
- Check thread dumps
- Look for blocked threads
- Analyze locks
- Identify contention
Interview line:
“Performance issues often come from thread contention.”
Scenario 2: CPU usage high but throughput low
Possible causes:
- Too many threads
- Context switching
- Lock contention
Solution:
- Reduce thread count
- Use executor
- Improve locking strategy
Scenario 3: Data inconsistency in production
Fix:
- Identify shared mutable state
- Apply synchronization or immutability
- Use concurrent collections
🟦 PART 9: SENIOR-LEVEL CONCEPTS
Q17. What is Immutable Object and why important?
Answer:
Immutable objects:
- Cannot change after creation
- Naturally thread-safe
Example:
- String
- Wrapper classes
Interview line:
“Immutability is the simplest thread-safety.”
Q18. What is Happens-Before relationship?
Answer:
Defines memory visibility guarantees in Java.
Example:
- Unlock → lock ensures visibility
Senior interview line:
“Happens-before defines correctness, not execution order.”
🌐 Category 6: Java + Frameworks (Spring Context)
1. What is JVM (Java Virtual Machine)?
Definition:
JVM is a runtime engine that executes Java bytecode.
Java does not run directly on the operating system.
Instead, Java runs inside the JVM.
Responsibilities of JVM:
- Loads .class files
- Verifies bytecode
- Manages memory (Heap, Stack, GC)
- Executes bytecode
- Handles garbage collection
Key Point:
JVM makes Java platform-independent.
Interview Line:
“JVM executes Java bytecode, not Java source code.”
🔹 2. What is JRE (Java Runtime Environment)?
Definition:
JRE provides the environment required to run Java applications.
JRE includes:
- JVM
- Core Java libraries (java.lang, java.util, etc.)
What JRE can do:
✔ Run Java applications
❌ Cannot develop Java applications
Example:
If you only want to run a Java application, you need JRE.
Interview Line:
“JRE = JVM + Java libraries.”
🔹 3. What is JDK (Java Development Kit)?
Definition:
JDK is a complete Java development package.
JDK includes:
- JRE
- Development tools
Development tools in JDK:
- javac → compiler
- java → launcher
- javadoc
- jar
- Debugging tools
What JDK can do:
✔ Write Java code
✔ Compile Java code
✔ Run Java applications
Interview Line:
“JDK is required to develop Java applications.”
🔁 Relationship Between JDK, JRE, and JVM
JDK
└── JRE
└── JVM
Or simply:
- JDK ⊃ JRE ⊃ JVM
🧠 Simple Real-Life Analogy (Very Effective in Interviews)
Imagine a Kitchen 🍳
- JVM → Stove (does the actual cooking)
- JRE → Kitchen (stove + utensils)
- JDK → Full cooking setup (kitchen + recipe books + tools)
📊 Comparison Table (Interview-Friendly)
| Feature | JVM | JRE | JDK |
| Executes bytecode | ✅ | ✅ | ✅ |
| Contains JVM | ❌ | ✅ | ✅ |
| Contains libraries | ❌ | ✅ | ✅ |
| Compiler (javac) | ❌ | ❌ | ✅ |
| Used for development | ❌ | ❌ | ✅ |
| Used for running apps | ❌ | ✅ | ✅ |
⚠️ Common Interview Traps (Remember this)
❌ JVM does NOT contain compiler
❌ JRE cannot compile code
❌ JDK is not only a compiler
🎯 Final Interview Answer (Say this confidently)
“JVM executes Java bytecode.
JRE provides the runtime environment including JVM and libraries.
JDK provides development tools along with JRE to build Java applications.”
Can Java run without JDK?
Answer:
Yes, Java applications can run without JDK, but they cannot be developed without it.
- To run a Java application → JRE is sufficient
- To compile / develop Java code → JDK is required
Interview line:
“JRE is enough to run Java, but JDK is required to build Java.”
Q2. Can Java run without JVM?
Answer:
No ❌
Java cannot run without JVM.
JVM is responsible for:
- Executing bytecode
- Memory management
- Garbage collection
Without JVM:
- Bytecode has no execution engine
Interview line:
“No JVM means no Java execution.”
Q3. Is JVM platform-dependent or independent?
Answer:
- JVM is platform-dependent
- Java bytecode is platform-independent
Each OS has its own JVM implementation:
- Windows JVM
- Linux JVM
- macOS JVM
Interview trap:
Java is platform-independent because JVM is platform-dependent.
Q4. What happens if JVM is removed from JRE?
Answer:
JRE becomes useless ❌
Why?
- JRE’s main purpose is to run Java programs
- JVM is the execution engine
Without JVM:
- No bytecode execution
- No memory management
Q5. Can one system have multiple JVMs?
Answer:
Yes ✅
- Each Java application runs in its own JVM
- Multiple JVMs can run simultaneously on the same machine
Example:
- One JVM for Tomcat
- Another JVM for a batch job
Interview line:
“Each Java process has its own JVM instance.”
Q6. What happens if two Java programs run on the same JVM?
Answer:
By default, this does not happen.
- Each Java application starts its own JVM
- Sharing a JVM can cause:
- Class conflicts
- Memory issues
- Security risks
Q7. Is JRE still required in Java 11+?
Answer:
No separate JRE is required in Java 11+.
- JDK itself contains everything
- JRE is no longer distributed separately
Interview line:
“From Java 11 onwards, only JDK is required.”
Q8. What is JIT Compiler and where does it belong?
Answer:
JIT (Just-In-Time) compiler is part of JVM.
What JIT does:
- Converts bytecode into native machine code
- Improves performance
- Optimizes frequently executed code
Interview gold line:
“JIT improves performance by compiling hot code paths.”
Q9. Is Java purely compiled or interpreted?
Answer:
Java is both compiled and interpreted.
Flow:
.java → javac → bytecode → JVM → JIT → machine code
Interview line:
“Java uses hybrid compilation.”
Q10. What is HotSpot JVM?
Answer:
HotSpot is the default JVM implementation used by Oracle/OpenJDK.
Features:
- JIT compilation
- Adaptive optimization
- Garbage collection tuning
Interview line:
“HotSpot optimizes code that runs frequently.”
Q11. Why can’t JVM execute .java files directly?
Answer:
JVM understands only bytecode, not Java source code.
- .java → human-readable
- .class → JVM-readable
Compilation step is mandatory.
Q12. What is the role of ClassLoader in JVM?
Answer:
ClassLoader:
- Loads class files into memory
- Follows parent delegation model
Types:
- Bootstrap
- Extension
- Application
Interview line:
“ClassLoader ensures class isolation and security.”
Q13. Can we customize JVM behavior?
Answer:
Yes ✅ using JVM options.
Examples:
- Heap size (-Xmx, -Xms)
- GC type (-XX:+UseG1GC)
- Stack size
Interview line:
“JVM tuning is critical for high-performance applications.”
🧠 Final Interview Power Answer (Use This)
“JDK is for development, JRE is for running applications, and JVM is the execution engine.
Java is platform-independent because bytecode runs on platform-specific JVM implementations.”
🚀 Category 7: Tricky & Scenario-Based
Q13. Why is String immutable in Java?
- Answer: For security, caching, and thread-safety.
- Example: If Strings were mutable, changing a password string could affect multiple references.
Q14. Difference between == and .equals()?
==: Compares references..equals(): Compares values (can be overridden).- Example:java
String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false System.out.println(a.equals(b)); // true