← Home
☕Java Developer Interview Questions — Fresher to 5 YOEJava Dev InterviewNEW
🧠

JVM, Memory & GC

Heap, stack, garbage collectors · 20 questions

1

Can you describe the high-level architecture of the JVM?

Must Know🌱 Fresher
🏗 JVM — three big subsystems
.class files
     |
     v
+----------------+     +---------------------+     +-------------------+
| Class Loader   | --> | Runtime Data Areas   | <-- | Execution Engine   |
| Subsystem      |     | (Heap, Stack, Method | --> | (Interpreter, JIT, |
| load/link/init |     |  Area, PC, Native    |     |  Garbage Collector)|
+----------------+     |  Method Stack)       |     +-------------------+
                       +---------------------+
JVM
2

What is the difference between heap and stack memory in Java?

Must Know🌱 Fresher
🧠 Heap vs stack per thread
Heap (ONE, shared by all threads)
  +----------------------------------+
  |  new Person("Ada")   new int[10] |   <- all objects live here
  +----------------------------------+

Thread A's stack        Thread B's stack     (each thread gets its OWN stack)
  +----------------+       +----------------+
  | frame: main()  |       | frame: run()   |
  |  int x = 5     |       |  Person p -----+---> points into the shared heap
  |  Person p -----+-----> +----------------+
  +----------------+

Every object (even ones referenced only by local variables) lives on the heap; primitives and object references live on the stack, one frame per active method call, private to that thread — which is exactly why local variables never need synchronization but shared heap objects do.

MemoryHeapStack
3

What are the Young and Old generations, and Eden/Survivor spaces?

Must Know📊 Mid

Most JVM garbage collectors are generational — built on the empirical observation that most objects die young (a temporary object created inside a method, never referenced again after it returns).

🌱 Generational heap layout
Young Generation                              Old Generation
+------------+-----------+-----------+        +--------------------------+
|   Eden     | Survivor0 | Survivor1 |  --->   |  long-lived objects that |
| (new objs  |           |           | promote |  survived several minor |
|  allocated |           |           |         |  GCs                     |
|  here)     |           |           |         |                          |
+------------+-----------+-----------+        +--------------------------+
  Minor GC clears Eden, copies survivors      Major/Full GC -- expensive

New objects are allocated in Eden. A Minor GC copies survivors into a Survivor space (ping-ponging between the two Survivor spaces on each cycle); an object that survives enough cycles gets promoted to the Old Generation, which is collected far less often (and more expensively) via a Major/Full GC.

GCHeap
4

What is garbage collection, and how does the JVM decide what to collect?

Must Know🌱 Fresher

Garbage collection automatically reclaims heap memory occupied by objects that are no longer reachable — meaning there's no chain of references from a GC root (see the GC roots question) leading to that object anymore. The classic algorithm is mark-and-sweep: mark every object reachable from the roots (a graph traversal), then sweep (reclaim) everything unmarked. Modern collectors add generational collection, compaction (to avoid heap fragmentation), and concurrent/parallel phases to minimize how long application threads are paused.

GC
5

Can Java still have memory leaks despite automatic garbage collection?

Must Know📊 Mid

Yes — garbage collection only reclaims objects that are unreachable. If your code keeps a reference to an object it no longer actually needs, the GC has no way to know that and will never collect it — this is a "logical" memory leak, still very possible in a garbage-collected language.

  • Static collections that only ever grow — a static Map used as a cache with no eviction policy.
  • Unclosed resources holding native memory behind them (streams, connections) — not strictly heap, but the same category of "forgot to release."
  • Listener/callback registrations never unregistered — the observed object keeps the listener (and everything it references) alive forever.
  • Inner classes holding an implicit reference to their outer instance — e.g. a non-static inner class or anonymous class kept alive elsewhere, dragging the whole outer object along with it.
  • ThreadLocal values not cleaned up in pooled threads that live indefinitely.
Memory LeakGC
6

What is a "stop-the-world" pause?

Important📊 Mid

A stop-the-world pause is a point where the JVM freezes every application thread so the collector can safely inspect/move objects without the program mutating references underneath it. Even "concurrent" collectors like G1 and ZGC still need brief stop-the-world phases for certain bookkeeping steps — the goal of modern collectors is minimizing the duration and frequency of these pauses, not eliminating them entirely (ZGC gets closest, targeting sub-millisecond pauses regardless of heap size).

GC
7

What are the phases of class loading (loading, linking, initialization)?

Important📊 Mid
📦 Class loading phases
1. LOADING       -- find the .class bytes (disk, JAR, network) and create a Class object
2. LINKING
   a. Verification -- bytecode is safe/well-formed (no stack corruption, valid jumps)
   b. Preparation  -- static fields allocated, set to default values (0, null, false)
   c. Resolution   -- symbolic references (other classes/methods) resolved to real ones
3. INITIALIZATION -- static initializers and static field assignments actually run,
                      top-to-bottom, exactly once, triggered by first real use of the class
ClassLoaderJVM
8

What is the ClassLoader hierarchy and the parent delegation model?

Important📊 Mid
🪜 ClassLoader delegation (parent-first)
Bootstrap ClassLoader   (loads core java.* classes, written in native code)
      ^
      | parent
Platform/Extension ClassLoader   (loads JDK extension classes)
      ^
      | parent
Application ClassLoader   (loads your app's classpath/classes)

Request to load "MyClass":
  Application asks Platform asks Bootstrap first ("parent delegation")
  Bootstrap can't find it -> Platform can't find it -> Application loads it itself

Parent delegation means a class loader always asks its parent to try first, only loading it itself if every ancestor fails — this guarantees core classes like java.lang.String are always loaded by the trusted Bootstrap loader, and a malicious or accidental app-level class named java.lang.String can never shadow the real one.

ClassLoaderJVM
9

What are the different types of OutOfMemoryError?

Important📊 Mid
  • java.lang.OutOfMemoryError: Java heap space — too many live objects for the configured heap; often a real memory leak, or genuinely undersized -Xmx.
  • OutOfMemoryError: Metaspace — too many loaded classes (common with class-loader leaks — e.g. repeatedly hot-redeploying an app without unloading old classloaders).
  • OutOfMemoryError: GC overhead limit exceeded — the JVM is spending almost all its time doing GC and reclaiming almost no memory each time, so it gives up rather than thrash forever.
  • OutOfMemoryError: Unable to create new native thread — hit an OS-level limit on threads/native memory, often from creating far too many threads.
OutOfMemoryError
10

What causes a StackOverflowError?

Important🌱 Fresher

Each thread's stack has a fixed maximum size; every method call pushes a new frame onto it. StackOverflowError is thrown when that limit is exceeded — almost always caused by uncontrolled recursion (a recursive function missing or with an incorrect base case), though a legitimately very deep call chain without recursion can also trigger it on a constrained stack size.

StackOverflowError
11

What is JIT compilation, and how does it make Java fast?

Important📊 Mid

The JVM starts by interpreting bytecode directly (slower, but no compilation delay). The Just-In-Time compiler monitors execution and identifies "hot" methods — ones called frequently or looped over heavily — and compiles those specific methods down to optimized native machine code at runtime, using actual observed behavior (branch frequencies, real argument types) to apply optimizations an ahead-of-time compiler couldn't know about in advance (like aggressively inlining a virtual call that's, in practice, only ever one concrete type). This is why long-running Java processes tend to get faster the longer they run — the JIT keeps recompiling hotter code paths with better-informed optimizations.

JITJVM
12

What is the difference between a Minor GC and a Major/Full GC?

Important📊 Mid

A Minor GC collects only the Young Generation (Eden + Survivor spaces) — fast and frequent, since most objects there die quickly. A Major GC (often used interchangeably with "Full GC," though some collectors distinguish them) collects the Old Generation, which holds long-lived objects — far less frequent, but much more expensive since it has to scan a much larger, denser region and typically involves longer stop-the-world pauses. A rising rate of Major/Full GCs is usually a red flag for either a memory leak or a heap sized too small for the application's working set.

GC
13

What garbage collector algorithms does the JVM offer (Serial, Parallel, G1, ZGC), and how do they differ?

Advanced📊 Mid
CollectorApproachGood for
SerialSingle-threaded, stop-the-worldSmall heaps, single-core environments
Parallel (Throughput)Multi-threaded, still stop-the-worldBatch jobs prioritizing total throughput over pause time
CMS (deprecated/removed)Mostly-concurrent, low pause, no compactionWas used for low-latency before G1 matured
G1 (default since Java 9)Region-based, concurrent + incremental compactionBalanced throughput/latency for most modern server apps
ZGC / ShenandoahFully concurrent, sub-millisecond pauses even on huge heapsVery large heaps, strict low-latency requirements

See the JVM / GC Overview deep dive → for how G1's region-based collection actually works.

GC
14

What are strong, weak, soft, and phantom references?

Advanced📊 Mid
Reference typeGC behaviorTypical use
Strong (normal reference)Never collected while reachableEveryday object references
Soft (SoftReference)Collected only when the JVM is genuinely low on memory, before throwing OOMMemory-sensitive caches
Weak (WeakReference)Collected on the very next GC cycle if no strong references remainWeakHashMap keys, avoiding accidental retention
Phantom (PhantomReference)Already finalized/unreachable; get() always returns null — used only to be notified via a reference queue after cleanupPost-mortem cleanup scheduling (Cleaner API)
ReferencesGC
15

What is escape analysis, and how does it let the JVM avoid heap allocation?

Advanced⭐ Experienced

Escape analysis is a JIT optimization that determines whether an object's reference ever "escapes" the method/thread that created it (is it returned, stored in a field, passed to another thread?). If the JIT proves an object never escapes, it can allocate it on the stack instead of the heap (or even eliminate the allocation entirely, keeping its fields in registers) — since a stack-only object is automatically reclaimed when the method returns, with zero GC involvement. This is why creating small, short-lived helper objects inside a hot method is often far cheaper than it looks on paper — the JIT may optimize the allocation away entirely.

JITEscape Analysis
16

What are GC roots?

Advanced📊 Mid

GC roots are the starting points of the reachability graph the collector traverses — any object not reachable by following references transitively from a GC root is garbage. Common GC roots:

  • Local variables and parameters currently on any thread's stack.
  • Active JNI (native code) references.
  • Static fields of loaded classes.
  • Objects used for synchronization that are currently being waited/notified on.
GC
17

What is the difference between PermGen and Metaspace?

Optional📊 Mid

Before Java 8, class metadata (loaded class definitions, method bytecode, constant pools) lived in PermGen, a fixed-size region carved out of the JVM's memory — chronically prone to OutOfMemoryError: PermGen space in applications that loaded many classes dynamically (classic app-server hot-redeploy scenarios). Java 8 replaced it with Metaspace, which lives in native (off-heap) memory and grows automatically up to the available system memory (or a configured cap via -XX:MaxMetaspaceSize) instead of a fixed region — removing the most common cause of that specific OOM.

MetaspaceJVM
18

Why was Object.finalize() deprecated, and what replaced it?

Optional📊 Mid

Object.finalize() was deprecated (Java 9) and slated for removal because it was fundamentally unreliable: the JVM gives no guarantee about when (or even if) it runs, it can silently swallow exceptions, resurrect "dead" objects, and meaningfully slow down garbage collection for objects that override it. The replacement, the java.lang.ref.Cleaner API, uses phantom references and a background thread to run cleanup actions more predictably and without most of finalize()'s pitfalls — though the strong recommendation either way is to use try-with-resources for deterministic cleanup whenever possible, rather than relying on either mechanism.

FinalizeCleaner
19

What do the -Xms and -Xmx JVM flags control?

Optional🌱 Fresher

-Xms sets the JVM's initial heap size at startup; -Xmx sets the maximum heap size it's allowed to grow to. Setting them equal (-Xms4g -Xmx4g) is a common production practice — it avoids the overhead of the heap resizing itself at runtime and makes memory behavior more predictable, at the cost of reserving that memory upfront even if the app doesn't need it yet.

JVM Flags
20

How would you diagnose a memory leak in a running Java application?

Optional📊 Mid
  • Heap dump (jmap, or triggered automatically via -XX:+HeapDumpOnOutOfMemoryError) analyzed in a tool like Eclipse MAT or VisualVM — look for object counts/retained size that keep growing across dumps, and trace the dominant "retained by" path back to what's holding the reference.
  • GC logs (-Xlog:gc*) — a rising trend in Old Generation occupancy after each Full GC (instead of dropping back down) is the classic leak signature.
  • Profilers (async-profiler, JFR/Java Flight Recorder, VisualVM) — sample allocations over time to see which code paths are allocating (and retaining) the most.
Memory LeakTooling