JVM and Memory Interview Questions

Naveen AnamaneniUpdated · 6 min read

You can drive a car for years without opening the bonnet. But when it starts making a strange noise on a highway, the driver who knows roughly what the engine, gearbox and radiator do is the one who gets home. The JVM is Java's engine. Most days you don't think about it, but when a program runs out of memory, pauses for seconds or starts slowly, understanding the JVM is what lets you fix it. That is why senior and mid-level interviews ask about it. This page collects the JVM and memory questions asked most often, from basic to advanced.

Basic Questions

What does the JVM do?

It loads .class files, verifies the bytecode, runs it (first with an interpreter, then compiling hot code with the JIT compiler), manages memory and garbage collection, and handles threads. It is what makes Java "write once, run anywhere".

What are the main memory areas of the JVM?

The heap (all objects, shared by threads), a stack per thread (method frames with local variables), Metaspace (class metadata, in native memory), the program counter per thread, the native method stack, and the code cache for JIT-compiled code.

What is the difference between stack and heap?

The stack is per thread, holds local variables and references, and is freed automatically when a method returns; too many nested calls cause StackOverflowError. The heap is shared, holds objects, and is cleaned by the garbage collector; running out causes OutOfMemoryError.

What is garbage collection?

Automatic freeing of objects that are no longer reachable from any live reference (local variables, static fields, active threads). You can't force it; System.gc() is only a hint.

Intermediate Questions

How does class loading work?

Classes are loaded lazily, the first time they are used, in three phases: loading (find and read the bytes), linking (verify, prepare static fields, resolve references) and initialization (run static initializers). Loaders form a hierarchy: bootstrap, platform, then application.

What is the parent delegation model?

A class loader first asks its parent to load a class and only loads it itself if the parent can't. This makes sure core classes such as java.lang.String always come from the JDK and can't be replaced by application code.

What is generational garbage collection?

The heap is split into a young generation for new objects and an old generation for long-lived ones. Most objects die young, so collecting the young generation often and cheaply is efficient; survivors are promoted to the old generation.

What is the JIT compiler?

The just-in-time compiler watches which methods run often ("hot" code) and compiles them to optimized machine code while the program runs, using techniques such as inlining and escape analysis. This is why Java programs speed up after a warm-up period.

What are -Xms, -Xmx and -Xss?

-Xms sets the initial heap size, -Xmx the maximum heap size, and -Xss the stack size per thread. For example, java -Xms512m -Xmx2g App.

Advanced Questions

Which garbage collectors does Java 25 offer?

G1 (the default, balanced throughput and pause times), ZGC (very short pauses, even with huge heaps; generational by default since Java 23), Parallel (maximum throughput, longer pauses), Serial (single-threaded, small heaps), and Shenandoah (low pauses, in some JDK builds).

What causes a memory leak in Java if there is a garbage collector?

Objects that are still reachable but no longer needed: entries left in a static Map or cache, listeners that are never removed, ThreadLocal values in pooled threads, or unclosed resources. The GC only frees unreachable objects.

How do you investigate an OutOfMemoryError?

Read the message (Java heap space, Metaspace, and so on). Run with -XX:+HeapDumpOnOutOfMemoryError, then open the heap dump in a tool such as Eclipse MAT or VisualVM to find which objects fill the heap and what keeps them alive. JDK Flight Recorder and jcmd GC.heap_info help too.

What are strong, soft, weak and phantom references?

A strong reference keeps an object alive. A soft reference is cleared when memory runs low (useful for caches). A weak reference is cleared at the next GC once only weak references remain (WeakHashMap). A phantom reference tells you after an object is finalized, for cleanup (Cleaner).

What is escape analysis?

A JIT optimization that checks whether an object can be seen outside the method that created it. If it can't "escape", the JIT can avoid allocating it on the heap at all, splitting it into local values, which reduces GC work.

Memory Errors in Code

Let's see the two classic memory errors and the information the JVM gives you about memory.

MemoryFacts.java▶ Try it
public class MemoryFacts {
    static int depth = 0;
 
    static void recurse() {
        depth++;
        recurse();                         // no base case
    }
 
    public static void main(String[] args) {
        try {
            recurse();
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError after many calls: "
                    + (depth > 1000));
        }
 
        Runtime rt = Runtime.getRuntime();
        System.out.println("max heap set: " + (rt.maxMemory() > 0));
        System.out.println("processors seen: "
                + (rt.availableProcessors() > 0));
 
        try {
            long[][] chunks = new long[1_000][];
            for (int i = 0; i < chunks.length; i++) {
                chunks[i] = new long[100_000_000];   // 800 MB each
            }
        } catch (OutOfMemoryError e) {
            System.out.println("OutOfMemoryError: " + e.getMessage());
        }
    }
}
Output
StackOverflowError after many calls: true
max heap set: true
processors seen: true
OutOfMemoryError: Java heap space

Explanation:

  1. recurse never stops, so each call adds a frame to the thread's stack until it is full and the JVM throws StackOverflowError.
  2. Runtime reports the maximum heap (set by -Xmx or a default based on the machine's memory) and the number of processors.
  3. Asking for many 800 MB arrays quickly exceeds the maximum heap, and the JVM throws OutOfMemoryError: Java heap space. Catching these errors is only for demonstration; real programs should fix the cause.

Interview Corner

A service becomes slow every few minutes. What would you check?

Garbage collection first: enable GC logging (-Xlog:gc) or record with JDK Flight Recorder and look for long pauses or a heap that keeps growing. Then check thread dumps (jcmd <pid> Thread.print) for blocked threads, and profile CPU usage.

Practice

  1. Easy: Run MemoryFacts with -Xss256k and with -Xss4m, printing depth in the catch. How does the stack size change the depth?
  2. Harder: Write a program that keeps adding objects to a static List in a loop. Run it with -Xmx64m -XX:+HeapDumpOnOutOfMemoryError and open the dump in VisualVM or Eclipse MAT.

Quick check: JVM and memory

4 questions
1Where are objects allocated?
2What does -Xmx set?
3Which is the default garbage collector in Java 25?
4Can a Java program leak memory?

Key Takeaways

Was this tutorial helpful?

Lesson 576 of 578