Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsJava Basics, JVM & Memory
✓ FreeBeginner· 10 min read

JVM Memory & Garbage Collection — Interview Questions

Heap vs stack, Metaspace, how garbage collection works, finalize(), GC algorithms, memory leaks, weak and soft references, and Java Flight Recorder.

Published September 25, 2026


How to use this lesson

Memory questions separate candidates who memorised a diagram from those who understand what happens when their code runs. For freshers, interviewers want clear definitions and one concrete example each. Add the "key points" when they dig deeper.

Q1. What memory areas does the JVM have?

Short answer: The heap (objects), the method area / Metaspace (class metadata), and, per thread, a Java stack, a program counter register and a native method stack.

Key points to cover:

  • Heap: every object and array lives here. It's shared by all threads, managed by the garbage collector, and usually split into a young generation (new objects) and an old generation (long-lived objects).
  • Java stack (one per thread): one frame per method call, holding local variables, parameters and partial results. The frame is popped when the method returns.
  • Metaspace (Java 8+): class metadata, method bytecode and the runtime constant pool. It replaced PermGen and lives in native memory, so it grows as needed unless you cap it with -XX:MaxMetaspaceSize.
  • PC register: the address of the current bytecode instruction, per thread.
  • Native method stack: used when Java calls native (C/C++) code through JNI.
void placeOrder() {
    int quantity = 3;                        // primitive local → lives in this method's stack frame
    Order order = new Order(quantity);       // reference 'order' on the stack; the Order object on the heap
}                                            // frame popped; the Order becomes unreachable → eligible for GC

Common trap: saying "objects are stored on the stack". References can be; the objects themselves go on the heap. (The JIT's escape analysis can scalar-replace an object that never leaves a method, but that's an optimisation, not the model.)

Learn it in depth → JVM Memory Areas

Q2. Which is faster, stack or heap, and why?

Short answer: The stack is cheaper. Allocation and deallocation are just moving the stack pointer, frames are freed automatically when a method returns, and the data is thread-private and usually hot in the CPU cache. Heap objects must eventually be tracked and reclaimed by the garbage collector.

Key points to cover:

  • Heap allocation in HotSpot is also fast: each thread allocates from its own TLAB (thread-local allocation buffer) by bumping a pointer. The real cost of the heap is garbage collection and poorer cache locality, not the new itself.
  • The stack is small (commonly 512 KB–1 MB per thread, set with -Xss). Deep or infinite recursion causes a StackOverflowError. Running out of heap causes an OutOfMemoryError: Java heap space.

Learn it in depth → JVM Memory Areas

Q3. What is garbage collection in Java, and how does it work?

Short answer: Garbage collection is the JVM's automatic memory management. It finds objects that are no longer reachable from any GC root and reclaims their memory, so you never free memory manually.

Key points to cover:

  • GC roots: local variables on thread stacks, static fields, active threads, and JNI references. Anything not reachable from a root is garbage. Cycles don't matter: two objects referring only to each other are still collected.
  • Generational hypothesis: most objects die young. New objects go into the young generation (Eden plus two survivor spaces), where minor GCs are frequent and cheap. Objects that survive several collections are promoted to the old generation, which is collected less often.
  • Phases: mark the live objects, then either sweep the dead ones, compact the live ones together, or copy the live ones to a fresh area.
  • You can request a collection with System.gc(), but the JVM may ignore it. Never rely on it.

Common trap: saying "an object is collected when its reference is set to null". Setting a variable to null only removes one reference. The object becomes eligible once it's unreachable, and the GC decides when to reclaim it.

Learn it in depth → Garbage Collection Fundamentals

Q4. What is the role of finalize() in garbage collection?

Short answer: finalize() was a hook the GC could call before reclaiming an object, meant for releasing resources. It is deprecated (since Java 9, and marked for removal in Java 18), and you should never rely on it.

Key points to cover:

  • There's no guarantee when, or even whether, finalize() runs. The JVM can exit first.
  • It slows collection down, because objects with finalizers need an extra GC cycle, and it can accidentally "resurrect" objects.
  • Modern alternatives:
    • try-with-resources with AutoCloseable, for deterministic cleanup.
    • java.lang.ref.Cleaner, as a safety net for native resources.
try (var reader = Files.newBufferedReader(path)) {   // closed automatically, even on exceptions
    return reader.readLine();
}

Common trap: describing finalize() as the way to close files or connections. Interviewers use this question to check that you know it's deprecated.

Learn it in depth → Garbage Collection Fundamentals

Q5. Which algorithms and collectors does the JVM use?

Short answer: The core algorithms are mark-sweep, mark-compact and copying (used for the young generation). The HotSpot collectors combine them: Serial, Parallel, G1 (the default since Java 9), and the low-pause ZGC and Shenandoah.

Key points to cover:

CollectorBest forNotes
SerialSmall heaps, single CPU, containers with 1 coreOne thread; stop-the-world
ParallelBatch jobs that want maximum throughputMulti-threaded; longer pauses
G1General-purpose defaultRegion-based; aims for a pause target (-XX:MaxGCPauseMillis)
ZGC / ShenandoahLarge heaps, latency-sensitive servicesMostly concurrent; pauses of about a millisecond
  • CMS was removed in Java 14. Mention that if the interviewer brings it up.
  • Choose a collector with flags such as -XX:+UseZGC. Generational ZGC became the default ZGC mode in Java 23.

Learn it in depth → Modern Garbage Collectors

Q6. How can memory leaks happen in Java if there's automatic garbage collection?

Short answer: The GC only frees unreachable objects. A leak happens when objects you no longer need stay reachable, so they're never collected and memory keeps growing.

Key points to cover:

  • Common causes:
    • Static collections or caches that only grow.
    • Listeners or callbacks that are registered and never removed.
    • ThreadLocal values that aren't cleared in thread pools.
    • Unclosed resources.
    • Inner classes holding a hidden reference to their outer object.
    • Keys with a broken hashCode/equals piling up in a HashMap.
  • Symptoms: heap usage that keeps climbing after each full GC, then OutOfMemoryError.
  • Diagnosis: take a heap dump (jcmd <pid> GC.heap_dump), and analyse it in Eclipse MAT or VisualVM. Look at the dominator tree and the paths to GC roots.
class SessionRegistry {
    private static final Map<String, Session> SESSIONS = new HashMap<>();
    static void login(Session s) { SESSIONS.put(s.id(), s); }
    // no logout/expiry → every session ever created stays reachable forever: a leak
}

Learn it in depth → Memory Leaks in Java

Q7. What are weak references and soft references?

Short answer: They're references that don't stop an object from being collected.

  • A weak reference is cleared at the next GC once no strong references remain.
  • A soft reference is kept until the JVM is running low on memory. That makes it suitable for memory-sensitive caches.

Key points to cover:

  • The strength order is strong → soft → weak → phantom.
  • WeakHashMap holds its keys weakly. An entry disappears once the key is no longer strongly referenced elsewhere. It's handy for attaching metadata to objects you don't own.
  • Phantom references (with a ReferenceQueue) tell you after an object is collected. They're the basis of Cleaner.
  • For real caches, prefer a library such as Caffeine, with size and time-based eviction. Soft-reference caches behave unpredictably under memory pressure.
WeakReference<byte[]> ref = new WeakReference<>(new byte[1024]);
System.gc();
System.out.println(ref.get());   // very likely null: nothing strongly references the array

Learn it in depth → Memory Leaks in Java

Q8. What is Java Flight Recorder (JFR)?

Short answer: JFR is a profiling and event-recording framework built into the JVM. It captures GC pauses, allocations, lock contention, I/O, CPU samples and exceptions with very low overhead (typically around 1%), so it's safe to run in production.

Key points to cover:

  • Start it at launch with -XX:StartFlightRecording=duration=60s,filename=app.jfr, or on a running process with jcmd <pid> JFR.start.
  • Analyse the recording in JDK Mission Control (JMC).
  • It's free and open source since Java 11. Before that, it was a commercial feature.
  • Use it to answer questions like "why did latency spike at 3 pm?" (GC pause? lock contention?) or "what's allocating so much memory?"

Learn it in depth → GC Tuning & Diagnostics

Q9. What is the difference between the Young Generation and the Old Generation?

Short answer: The Young Generation is where new objects are allocated. It's collected often, with fast minor GCs. The Old (tenured) Generation holds objects that have survived several young collections. It's collected less often, and collecting it is more expensive.

Key points to cover:

  • The Young Generation is split into Eden plus two survivor spaces:
    • New objects go into Eden.
    • Each minor GC copies live objects into a survivor space, and increments their age.
    • Objects that pass the age threshold (-XX:MaxTenuringThreshold), or that are too big for the survivor spaces, are promoted to the Old Generation.
  • This works because most objects die young: minor GCs copy only the few survivors, so they're cheap.
  • Warning signs:
    • Objects promoted prematurely (survivor spaces too small, or very high allocation rates) fill the old generation and cause long major or full GCs.
    • An old generation that keeps growing after every full GC usually means a memory leak.
  • G1 keeps the same generational idea, but uses many equal-sized regions instead of fixed contiguous spaces.

Learn it in depth → Garbage Collection Fundamentals

Follow-up questions this topic invites — and their answers

Q: What's the difference between StackOverflowError and OutOfMemoryError? A: A StackOverflowError means one thread's stack is exhausted, almost always from runaway recursion. An OutOfMemoryError means the JVM couldn't allocate memory: heap space, Metaspace, or native memory for new threads. Both are Errors, not exceptions, and you normally don't catch them.

Q: What are -Xms and -Xmx? A: The initial and maximum heap sizes. Many teams set them equal in production, so the heap doesn't resize at runtime. In containers, -XX:MaxRAMPercentage sizes the heap relative to the container's memory limit.

Q: What is a "stop-the-world" pause? A: A moment when all application threads are paused so the GC can work safely. Modern collectors such as G1, ZGC and Shenandoah do most of their work concurrently, to keep these pauses short.

Q: Why did Java 8 replace PermGen with Metaspace? A: PermGen had a fixed maximum size, and applications that loaded many classes (app servers, frequent redeploys) hit OutOfMemoryError: PermGen space. Metaspace uses native memory and grows dynamically, which removed that tuning headache.

Q: Can you force garbage collection? A: No. System.gc() is only a request, and it can be disabled with -XX:+DisableExplicitGC. Code that depends on GC timing is broken by design.

Previous

JDK, JRE, JVM & the main Method — Interview Questions

Next

Data Types, Wrapper Classes & Equality — Interview Questions

AI Tutor

Lesson: JVM Memory & Garbage Collection — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.