☕ Core Java Technical Interview Questions & Answers
The ultimate, production-tested interview preparation guide covering Java Fundamentals, OOP, Collections internals, Concurrency, Exceptions, JVM internals, and Performance Tuning.
📌 Index of Topics Covered
| Section | Topic Category | Key Concepts Included |
|---|---|---|
| 1. Java Fundamentals | Core Syntax & Basics | JVM/JDK/JRE, Platform Independence, == vs equals(), hashCode() Contract, String Pool & Immutability, Pass-by-Value |
| 2. Object-Oriented Programming | OOP Architecture | Abstraction, Encapsulation, Dynamic Method Dispatch, Constructors, Static Method Hiding, Marker Interfaces, Abstract Class vs Interface |
| 3. Collections Framework | Data Structures & Internals | ArrayList vs LinkedList, HashMap Internals (Treeification, Resizing, Power-of-2 Capacity), ConcurrentHashMap, TreeMap, Fail-Fast vs Fail-Safe, CopyOnWriteArrayList |
| 4. Multithreading & Concurrency | Concurrent Programming | JMM, volatile, synchronized vs ReentrantLock, Deadlocks, wait/notify, CountDownLatch/CyclicBarrier/Semaphore, ThreadLocal, ExecutorService, CompletableFuture, Optimistic vs Pessimistic Locking |
| 5. Exception Handling | Error Management | Checked vs Unchecked, Try-With-Resources, Multiple Catches, Return in Finally, Exception Swallowing Anti-Pattern |
| 6. JVM & Performance Tuning | JVM Internals & Diagnostics | JVM Memory Areas (Heap, Stack, Metaspace), GC Algorithms (G1GC, ZGC, Shenandoah), OutOfMemoryError Troubleshooting, Production Bottleneck Diagnosis |
1. Java Fundamentals
Q1: What are the key features of Java?
Answer:
Answer:
- Platform Independent (Write Once, Run Anywhere): Compiles code into machine-neutral bytecode executed by JVM.
- Object-Oriented: Supports Abstraction, Encapsulation, Inheritance, and Polymorphism.
- Automatic Memory Management: Built-in Garbage Collection (GC) reclaims unreferenced heap memory.
- Robust & Secure: Strongly typed, no raw pointers, explicit exception handling, runtime bytecode verification.
- Multithreaded: Built-in language support for concurrent thread execution and async synchronization.
Q2: Explain the JVM, JDK, and JRE.
Answer:
Answer:
- JVM (Java Virtual Machine): Abstract computing machine that executes bytecode line-by-line using an interpreter and JIT compiler.
- JRE (Java Runtime Environment): The physical implementation of JVM + core class libraries (
rt.jar) required to run Java programs. - JDK (Java Development Kit): Full software development environment containing JRE + developer tools (
javaccompiler,jdbdebugger,javadoc).
Q3: How does Java achieve platform independence?
Answer: Java source code (
Answer: Java source code (
.java) is compiled by javac into an intermediate architecture-neutral format called Bytecode (.class file). The OS-specific JVM interprets/JIT-compiles this bytecode into machine-native instructions at runtime.
Q4: What are the differences between
Answer:
== and equals()?Answer:
==: Operator that compares primitive values directly, or compares memory reference addresses for objects (checks if both references point to the exact same heap memory location).equals(): Method defined inObjectclass (default performs==check). Classes likeString,Integer, and custom domain entities overrideequals()to evaluate logical content equality.
Q5: Explain
Answer: The
The hashCode Contract: 1. If two objects are equal according to
2. If two objects have the same
3. Overriding
hashCode() and its contract with equals().Answer: The
hashCode() method returns an integer hash value for an object, used by hash-based collections like HashMap and HashSet.The hashCode Contract: 1. If two objects are equal according to
equals(), they MUST have the exact same hashCode().2. If two objects have the same
hashCode(), they are NOT necessarily equal (Hash Collision).3. Overriding
equals() without overriding hashCode() breaks HashMap retrievals!
Q6: Why is String immutable in Java?
Answer:
Answer:
- String Constant Pool (SCP): Allows sharing identical String literals to save memory. Immutability guarantees shared literals won't be unexpectedly altered.
- Security: Strings carry critical network URLs, DB connection credentials, and file paths. Immutability prevents malicious tamper attempts.
- Thread Safety: Immutable strings can be shared freely across multiple threads without synchronization.
- HashCode Caching: Hashcode is calculated once at creation and cached, making String ideal for
HashMapkeys.
Q7: How is the String Pool implemented?
Answer: The String Constant Pool (SCP) is a special memory region inside the Heap (since Java 7, moved from PermGen). It is implemented as a fixed-capacity hash table storing references to unique String literals created using double quotes (e.g.,
Answer: The String Constant Pool (SCP) is a special memory region inside the Heap (since Java 7, moved from PermGen). It is implemented as a fixed-capacity hash table storing references to unique String literals created using double quotes (e.g.,
String s = "Java").
Q8: Difference between String, StringBuilder, and StringBuffer.
Answer:
Answer:
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | Thread-Safe | Not Thread-Safe | Thread-Safe (Synchronized) |
| Performance | Slow (creates new objects) | Fastest | Slower than StringBuilder |
Q9: What happens when you write
Answer: Exactly 1 or 2 objects are created:
1. The literal
2. The
Reference variable
String s = new String("Java")?Answer: Exactly 1 or 2 objects are created:
1. The literal
"Java" is placed into the String Constant Pool (if not already present).2. The
new String(...) operator forces the creation of a new distinct object in the main Heap memory.Reference variable
s points to the object in heap memory.
Q10: Explain Pass-by-Value in Java.
Answer: Java is strictly Pass-by-Value for all variables.
Answer: Java is strictly Pass-by-Value for all variables.
- For primitive arguments: A copy of the actual primitive value is passed to the method.
- For object reference arguments: A copy of the reference address (pointer) is passed to the method. Modifying internal object state affects the original object, but reassigning the reference variable inside the method does NOT change the original caller's reference.
2. Object-Oriented Programming (OOP)
Q11: Explain all 4 OOP principles with real-world examples.
Answer:
Answer:
- Abstraction: Hiding internal implementation details and exposing essential interfaces. Example: Driving a car using steering wheel and accelerator without knowing internal engine combustion physics.
- Encapsulation: Bundling data (fields) and methods into a single unit and restricting direct access via private modifiers and getters/setters. Example: Capsule pill enclosing internal medicine.
- Inheritance: Reusing code where a child class acquires properties and behavior from a parent class. Example:
ElectricCarextendingVehicle. - Polymorphism: Ability of an object to take many forms. Example: A single
draw()method behaving differently forCircleandRectangleobjects.
Q12: Difference between Abstraction and Encapsulation.
Answer:
Answer:
- Abstraction focuses on WHAT an object does rather than HOW it does it (Design level - interfaces/abstract classes).
- Encapsulation focuses on HOW to hide/secure the internal state of an object from unauthorized modification (Implementation level - access modifiers).
Q13: Method Overloading vs Method Overriding.
Answer:
Answer:
- Method Overloading: Same method name in the same class with different parameter lists (Compile-Time / Static Polymorphism).
- Method Overriding: Same method name and exact signature in subclass overriding superclass implementation (Runtime / Dynamic Polymorphism).
Q14: Can constructors be overridden?
Answer: No. Constructors are not members of a class and cannot be inherited by subclasses; therefore they cannot be overridden. However, constructors can be overloaded within the same class.
Answer: No. Constructors are not members of a class and cannot be inherited by subclasses; therefore they cannot be overridden. However, constructors can be overloaded within the same class.
Q15: What is Dynamic Method Dispatch?
Answer: The mechanism by which a call to an overridden method is resolved at runtime rather than compile time. The JVM inspects the actual object type in heap memory at runtime and dispatches execution to that object's method version using a Virtual Method Table (vtable).
Answer: The mechanism by which a call to an overridden method is resolved at runtime rather than compile time. The JVM inspects the actual object type in heap memory at runtime and dispatches execution to that object's method version using a Virtual Method Table (vtable).
Q16: Explain the
Answer:
super and this keywords.Answer:
this: Reference variable pointing to the current instance of the class. Used to invoke current class constructors (this()) or fields.super: Reference variable pointing to the immediate parent class instance. Used to invoke parent class constructors (super()) or overridden parent methods.
Q17: Can we override static methods? (Method Hiding vs Overriding)
Answer: No, static methods cannot be overridden because static methods are resolved statically at compile time based on the reference type. If a subclass defines a static method with the exact signature as a parent static method, it is called Method Hiding, not overriding.
Answer: No, static methods cannot be overridden because static methods are resolved statically at compile time based on the reference type. If a subclass defines a static method with the exact signature as a parent static method, it is called Method Hiding, not overriding.
Q18: What are Marker Interfaces? Give examples.
Answer: An interface that contains zero methods and zero fields. It is used to "mark" or tag a class so the JVM or frameworks know to grant special behavior.
Examples:
Answer: An interface that contains zero methods and zero fields. It is used to "mark" or tag a class so the JVM or frameworks know to grant special behavior.
Examples:
java.io.Serializable, java.lang.Cloneable, java.util.RandomAccess.
Q19: Interface vs Abstract Class (Java 8+).
Answer:
Answer:
- Abstract Class: Can maintain instance state (non-final fields), has constructors, can have
protectedmembers. A class can extend only 1 abstract class. - Interface (Java 8+): All fields are
public static final. Can havedefaultandstaticmethods (andprivatemethods since Java 9), but no instance state or constructors. A class can implement multiple interfaces.
Q20: Explain default and static methods in interfaces.
Answer: Introduced in Java 8:
-
-
Answer: Introduced in Java 8:
-
default methods: Allow adding new methods with concrete default implementations to interfaces without breaking existing implementing classes.-
static methods: Utility helper methods bound to the interface namespace, invoked via InterfaceName.method().
3. Collections Framework
Q21: Difference between ArrayList and LinkedList.
Answer:
Answer:
ArrayList: Backed by a dynamically resizing array. Provides $O(1)$ random access speed via index, but $O(N)$ insertion/deletion in the middle due to element shifting.LinkedList: Backed by a doubly-linked list. Provides $O(N)$ lookup access speed, but $O(1)$ node insertion/deletion once the position is located.
Q22: How does HashMap work internally in Java 8+?
Answer: HashMap is an array of buckets storing Linked Nodes (Node<K,V>).
1.
2. Nodes are placed into the bucket. On collision, items form a Linked List.
3. Treeification: When bucket collisions exceed 8 nodes (and table capacity >= 64), the bucket transforms into a Red-Black Tree, improving lookup from $O(N)$ to $O(\log N)$.
Answer: HashMap is an array of buckets storing Linked Nodes (Node<K,V>).
1.
hash(key) computes index: index = hash & (n - 1).2. Nodes are placed into the bucket. On collision, items form a Linked List.
3. Treeification: When bucket collisions exceed 8 nodes (and table capacity >= 64), the bucket transforms into a Red-Black Tree, improving lookup from $O(N)$ to $O(\log N)$.
Q23: What happens when two keys have the same hash code?
Answer: A Hash Collision occurs. Both key-value pairs are stored in the same array bucket as a linked list (or Red-Black tree node). During retrieval, HashMap traverses the bucket nodes using
Answer: A Hash Collision occurs. Both key-value pairs are stored in the same array bucket as a linked list (or Red-Black tree node). During retrieval, HashMap traverses the bucket nodes using
.equals() to identify the exact matching key.
Q24: Explain HashMap resizing and Load Factor.
Answer: The default **Load Factor** is
- Array capacity doubles (e.g. 16 → 32).
- All existing entries are rehashed into the new doubled array.
Answer: The default **Load Factor** is
0.75. When the total number of entries exceeds capacity * 0.75 (e.g. 12 entries for initial capacity 16), HashMap triggers **Resizing**:- Array capacity doubles (e.g. 16 → 32).
- All existing entries are rehashed into the new doubled array.
Q25: Why is the default initial capacity of HashMap 16 (Power of 2)?
Answer: Bitwise AND operation
Answer: Bitwise AND operation
hash & (n - 1) works as a fast modulo equivalent ONLY when n is a power of 2. It evenly distributes keys across buckets and is significantly faster than standard modulo (hash % n).
Q26: Difference between HashMap, Hashtable, and ConcurrentHashMap.
Answer:
Answer:
HashMap: Non-synchronized, allows 1 null key and multiple null values, fast, not thread-safe.Hashtable: Legacy, fully synchronized on every method (slow), no null keys/values allowed.ConcurrentHashMap: High concurrency, lock-striping per bucket node using CAS, no null keys/values allowed.
Q27: Explain ConcurrentHashMap internal working in Java 8+.
Answer: Eliminates whole-table locks. Uses CAS (Compare-And-Swap) for volatile bucket head assignments. When writing to a populated bucket, it locks ONLY the head node of that specific bucket using
Answer: Eliminates whole-table locks. Uses CAS (Compare-And-Swap) for volatile bucket head assignments. When writing to a populated bucket, it locks ONLY the head node of that specific bucket using
synchronized(bucketHead), allowing parallel concurrent writes across different buckets.
Q28: Difference between TreeMap and HashMap.
Answer:
Answer:
HashMap provides $O(1)$ performance, unordered elements. TreeMap implements NavigableMap backed by a Red-Black Tree, maintaining keys in sorted natural order or custom Comparator order with $O(\log N)$ operation speed.
Q29: Explain Fail-Fast vs Fail-Safe Iterators.
Answer:
Answer:
- Fail-Fast (e.g. ArrayList, HashMap): Iterates over original collection. Throws
ConcurrentModificationExceptionimmediately if collection is structurally modified during iteration. - Fail-Safe (e.g. CopyOnWriteArrayList, ConcurrentHashMap): Operates on a clone array or volatile view of data. Does NOT throw exception if modified during iteration.
Q30: When should you use CopyOnWriteArrayList?
Answer: When read operations heavily outnumber write operations (e.g., event listeners or cached configuration lists). Every write operation creates a brand new copy of the underlying array, making writes expensive ($O(N)$) but reads lock-free and super fast.
Answer: When read operations heavily outnumber write operations (e.g., event listeners or cached configuration lists). Every write operation creates a brand new copy of the underlying array, making writes expensive ($O(N)$) but reads lock-free and super fast.
4. Multithreading & Concurrency
Q31: What is the Java Memory Model (JMM)?
Answer: JMM defines the rules for thread communication and interaction with main memory vs CPU caches. It specifies guarantees around Visibility (changes by one thread visible to others), Atomicity, and Ordering (preventing compiler reordering bugs).
Answer: JMM defines the rules for thread communication and interaction with main memory vs CPU caches. It specifies guarantees around Visibility (changes by one thread visible to others), Atomicity, and Ordering (preventing compiler reordering bugs).
Q32: Explain volatile keyword.
Answer:
Answer:
volatile guarantees **Memory Visibility** by forcing threads to read/write variables directly to Main Memory rather than local CPU thread caches. It also establishes a Memory Barrier preventing instruction reordering. Note: Volatile does NOT guarantee atomicity for compound operations like count++ (use AtomicInteger instead).
Q33: Difference between
Answer:
synchronized and ReentrantLock.Answer:
synchronized: Implicit language keyword. Automatic lock acquisition/release, non-fair, cannot interrupt waiting threads.ReentrantLock: Explicit API class injava.util.concurrent.locks. OfferstryLock(timeout), fair lock option, interruptible lock acquisition, and multiple Condition variables.
Q34: What is Deadlock? How do you detect and avoid it?
Answer: Deadlock occurs when 2+ threads are blocked forever, each holding a lock the other thread needs.
- Detection: Use thread dumps via
- Prevention: Acquire locks in a strict global sequence, or use
Answer: Deadlock occurs when 2+ threads are blocked forever, each holding a lock the other thread needs.
- Detection: Use thread dumps via
jcmd <pid> Thread.print, jstack, or VisualVM.- Prevention: Acquire locks in a strict global sequence, or use
ReentrantLock.tryLock(timeout) instead of blocking indefinitely.
Q35: Difference between wait(), notify(), and notifyAll().
Answer: Methods of
-
-
-
Answer: Methods of
Object class executed inside a synchronized monitor block:-
wait(): Releases monitor lock and suspends thread until notified.-
notify(): Wakes up ONE arbitrary thread waiting on object monitor.-
notifyAll(): Wakes up ALL threads waiting on object monitor (prevents lost signals).
Q36: Explain CountDownLatch, CyclicBarrier, and Semaphore.
Answer:
Answer:
CountDownLatch: One-time synchronization barrier. Main thread waits until counter reaches zero as worker threads complete tasks.CyclicBarrier: Reusable barrier where N threads wait for each other to reach a common execution barrier before proceeding together.Semaphore: Controls access to a shared resource using a set of permits (e.g., database connection pool limits).
Q37: What is ThreadLocal and how to avoid memory leaks?
Answer: Provides thread-isolated variables. Each thread maintains an implicit copy of the variable.
Memory Leak Danger: In thread pools, threads are reused. If
Answer: Provides thread-isolated variables. Each thread maintains an implicit copy of the variable.
Memory Leak Danger: In thread pools, threads are reused. If
ThreadLocal.remove() is not explicitly called in a finally block, stale references remain in thread pool workers causing severe memory leaks!
Q38: How does ExecutorService improve thread management?
Answer: Prevents thread creation overhead by maintaining a reusable pool of worker threads (
Answer: Prevents thread creation overhead by maintaining a reusable pool of worker threads (
ThreadPoolExecutor). Manages task queues, thread lifecycles, and returns Future<V> results asynchronously.
Q39: Explain CompletableFuture.
Answer: Non-blocking asynchronous reactive programming API introduced in Java 8. Supports task chaining (
Answer: Non-blocking asynchronous reactive programming API introduced in Java 8. Supports task chaining (
thenApply, thenCompose), combining futures (thenCombine), exception handling (exceptionally), and parallel scatter-gather execution (allOf).
Q40: Difference between Optimistic and Pessimistic Locking.
Answer:
Answer:
- Pessimistic Locking: Assumes conflicts WILL happen. Locks records at database level (
SELECT FOR UPDATE) or synchronized code block, blocking others. - Optimistic Locking: Assumes conflicts are RARE. Does not lock records; checks a
@Versioncolumn before update. If version changed, throwsOptimisticLockException.
5. Exception Handling
Q41: Checked vs Unchecked Exceptions.
Answer:
Answer:
- Checked Exceptions: Subclasses of
Exception(excludingRuntimeException). Checked at compile time (e.g.,IOException,SQLException). Compiler forces try-catch or throws declaration. - Unchecked Exceptions: Subclasses of
RuntimeException. Occur at runtime due to logical bugs (e.g.NullPointerException,ArithmeticException). Compiler does not force explicit checks.
Q42: Explain Try-With-Resources.
Answer: Introduced in Java 7. Automatically closes resources declared in try statement parentheses (must implement
Answer: Introduced in Java 7. Automatically closes resources declared in try statement parentheses (must implement
AutoCloseable interface). Eliminates manual close() calls in finally blocks.
Q43: Can we have multiple catch blocks? What are the rules?
Answer: Yes. Specific subclass exceptions MUST be caught before general superclass exceptions (e.g.
Answer: Yes. Specific subclass exceptions MUST be caught before general superclass exceptions (e.g.
FileNotFoundException before IOException); otherwise compiler throws "exception has already been caught" error. Since Java 7, multi-catch (catch (IOException | SQLException e)) is also supported.
Q44: What happens if both try and finally blocks return a value?
Answer: The value returned by the
Answer: The value returned by the
finally block OVERRODES and swallows the value returned by the try block (and swallows any unhandled exception thrown in try!). Best practice: Never return values inside a finally block.
Q45: Why should exceptions not be swallowed (Swallowing Exceptions Anti-Pattern)?
Answer: Swallowing exceptions (empty catch blocks
Answer: Swallowing exceptions (empty catch blocks
catch(Exception e) {{}}) hides critical system failures, corrupts application state silently, and makes root-cause debugging impossible in production.
6. JVM & Performance Tuning
Q46: Explain JVM Memory Areas.
Answer:
Answer:
- Heap Memory: Shared across all threads, stores object instances and arrays.
- Stack Memory: Thread-private, stores method stack frames, primitive local variables, and object references.
- Metaspace (Native Memory): Replaced PermGen in Java 8. Stores class metadata, bytecode definitions, and method data.
- Program Counter (PC) Register: Thread-private, tracks current executing JVM instruction address.
- Native Method Stack: Stores C/C++ native method call stack frames.
Q47: How does Garbage Collection work?
Answer: GC operates on the **Weak Generational Hypothesis** (most objects die young).
1. Mark: Identifies reachable live objects starting from GC Roots.
2. Sweep: Reclaims memory occupied by unreferenced dead objects.
3. Compact: Relocates live objects to eliminate memory fragmentation.
Answer: GC operates on the **Weak Generational Hypothesis** (most objects die young).
1. Mark: Identifies reachable live objects starting from GC Roots.
2. Sweep: Reclaims memory occupied by unreferenced dead objects.
3. Compact: Relocates live objects to eliminate memory fragmentation.
Q48: What causes OutOfMemoryError and how do you troubleshoot it?
Answer:
-
-
Troubleshooting: Add JVM flag
Answer:
-
java.lang.OutOfMemoryError: Java heap space: Heap full due to memory leak or undersized -Xmx.-
java.lang.OutOfMemoryError: Metaspace: Too many classes loaded dynamically.Troubleshooting: Add JVM flag
-XX:+HeapDumpOnOutOfMemoryError. Analyze the generated .hprof memory dump file using Eclipse Memory Analyzer (MAT) to locate leaky object reference paths.
Q49: Explain different GC algorithms (G1, ZGC, Shenandoah, Parallel GC).
Answer:
Answer:
- Parallel GC: Multi-threaded stop-the-world collector focused on maximum throughput.
- G1GC (Garbage-First): Region-based collector balancing pause times and throughput. Default in Java 9+.
- ZGC: Ultra-low latency concurrent collector handling multi-terabyte heaps with <1ms pause times.
- Shenandoah: Low-pause concurrent GC performing compaction concurrently with running application threads.
Q50: How would you diagnose a Java application that is slow in production?
Answer: 1. Check CPU & Memory Metrics: Use
2. Take Thread Dumps: Run
3. Inspect Garbage Collection Logs: Enable
4. Profile with APM Tools: Use Async-Profiler, JDK Flight Recorder (JFR), Datadog, or NewRelic to identify database latency, CPU hot spots, or slow external calls.
Answer: 1. Check CPU & Memory Metrics: Use
top, htop, Prometheus/Grafana.2. Take Thread Dumps: Run
jcmd <pid> Thread.print to check for blocked threads or lock contention.3. Inspect Garbage Collection Logs: Enable
-Xlog:gc* to detect frequent Stop-The-World pause spikes.4. Profile with APM Tools: Use Async-Profiler, JDK Flight Recorder (JFR), Datadog, or NewRelic to identify database latency, CPU hot spots, or slow external calls.