LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 5 of 13

JVM, Memory and Garbage Collection

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

A mental model of the JVM

Think of three layers: class loading brings code in, the runtime data areas (stacks, heap, metaspace) hold it, and the execution engine (interpreter, JIT, GC) runs and cleans it. Every JVM question maps to one of these layers.

  • Memory areasStack, heap, metaspace and what lives where.
  • Garbage collectionReachability, generations, G1 and ZGC.
  • TroubleshootingHeap dumps, GC logs and leak patterns.

JVM questions show whether you understand what happens after you press Run. You do not need to know every flag; you need a clear mental model of memory areas, how objects die, and how to investigate when memory keeps growing in production.

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

The JVM runs bytecode. The JRE is the JVM plus the core libraries needed to run programs. The JDK is the JRE plus development tools such as javac, jdb and jcmd. Since Java 11 there is no separate JRE download; you install a JDK and can build a trimmed runtime with jlink.


2. Explain heap and stack memory with an example.

Each thread has its own stack, which holds method frames: local variables, parameters and references. Objects live on the shared heap. When a method returns, its frame is popped instantly; heap objects stay until the garbage collector finds them unreachable.

void placeOrder() {
    int qty = 2;                       // stack (primitive local)
    Order order = new Order(qty);      // reference on the stack, object on the heap
}                                      // frame gone; Order is now eligible for GC

3. How does garbage collection decide what to delete?

The collector starts from GC roots — local variables on thread stacks, static fields, active threads — and marks everything reachable from them. Whatever is not reachable is garbage, even if objects point to each other in a cycle. Most collectors are generational: new objects go to the young generation, which is collected often and cheaply, because most objects die young.


4. Which garbage collectors should you know about?

G1 is the default since Java 9: it splits the heap into regions and aims for predictable pause times. ZGC (generational since Java 21) keeps pauses under a millisecond even on very large heaps. Parallel GC maximises throughput for batch jobs. Serial GC suits tiny containers. In an interview, say which you would pick for a low-latency API (ZGC or G1) versus a nightly batch (Parallel).


5. Can Java have memory leaks if it has a garbage collector?

Yes. A leak in Java is an object that is still reachable but no longer needed, so the GC cannot remove it. Common causes: static collections that only grow, caches without eviction, listeners never unregistered, ThreadLocal values in pools, and unclosed resources.

class AuditLog {
    private static final List<String> EVENTS = new ArrayList<>();
    static void record(String e) { EVENTS.add(e); }   // grows forever → OutOfMemoryError
}

6. How would you investigate an OutOfMemoryError in production?

Start with the message: Java heap space, Metaspace and unable to create native thread point to different problems. Run with -XX:+HeapDumpOnOutOfMemoryError, open the dump in Eclipse MAT or VisualVM, and look at the dominator tree to find what retains the most memory. Check GC logs for steadily rising old-generation usage after each collection — the signature of a leak.

java -Xms512m -Xmx2g \
     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps \
     -Xlog:gc*:file=/var/log/gc.log \
     -jar orders-service.jar

7. What does the class loader do?

Class loaders load .class files into the JVM on first use. They follow a parent delegation model: the application loader asks the platform loader, which asks the bootstrap loader, before loading a class itself. This stops your code from replacing core classes such as java.lang.String.


8. What is the JIT compiler?

The JVM starts by interpreting bytecode, profiles which methods run often (“hot” code), and compiles those to optimised machine code with the Just-In-Time compiler. That is why Java services get faster after warm-up and why micro-benchmarks need a warm-up phase (use JMH, not System.nanoTime() loops).


Remember

Key points

  • Reachability decides life

    GC deletes unreachable objects, cycles included.

  • Leaks are reachable garbage

    Growing static maps and caches are the usual suspects.

  • G1 is the default

    ZGC for very low pauses; Parallel for throughput.

  • Measure before tuning

    Read GC logs and heap dumps before changing flags.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between StackOverflowError and OutOfMemoryError? Basic

    StackOverflowError means one thread's stack is full, usually from runaway recursion. OutOfMemoryError means the heap (or metaspace, or native memory) cannot satisfy an allocation.

  2. 2 What replaced PermGen in Java 8? Intermediate

    Metaspace, which stores class metadata in native memory and grows dynamically. Cap it with -XX:MaxMetaspaceSize if class-loader leaks are a risk.

  3. 3 Does calling System.gc() force garbage collection? Basic

    No, it is only a hint, and many production setups disable it. Code should never depend on it.

  4. 4 What are strong, soft, weak and phantom references? Advanced

    Strong references keep objects alive. Soft references are cleared only when memory is low (useful for caches). Weak references are cleared at the next GC (as in WeakHashMap). Phantom references tell you after an object is collected, for cleanup work.

  5. 5 Why does a Java service use more memory than -Xmx? Advanced

    -Xmx limits only the heap. Thread stacks, metaspace, the code cache, direct buffers and GC structures use native memory on top of it — plan container limits with headroom.

    Key insight: Container memory = heap + non-heap + headroom.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links