How Does Garbage Collection Work in Java?
Learn how Java garbage collection works — reachability, GC roots, the generational heap, minor vs major GC, collectors like G1 and ZGC, plus interview Q&A.
Expected Interview Answer
Garbage collection in Java is the automatic process by which the JVM reclaims heap memory occupied by objects that are no longer reachable from any live reference, freeing developers from manual memory management.
The JVM tracks object reachability starting from GC roots (stack variables, static fields, active threads). Objects not reachable through any chain of references are eligible for collection. Modern collectors use a generational model: new objects are allocated in the Young generation (Eden and survivor spaces) and collected by frequent, cheap minor GCs; objects that survive are promoted to the Old generation, cleaned by less frequent major GCs. Algorithms like G1, Parallel, and ZGC differ in how they balance throughput and pause times, but all rely on mark-and-sweep style reachability plus compaction.
- Automatic reclamation prevents most memory leaks
- Eliminates manual free() and dangling-pointer bugs
- Generational design makes short-lived objects cheap to collect
- Compaction reduces heap fragmentation
- Pluggable collectors let you tune for throughput or low pause
AI Mentor Explanation
Think of ground staff clearing the field between innings: any kit still linked to an active player stays, but abandoned gear with no owner is swept away. The JVM does the same by tracing from live references (the players) and removing objects nothing points to. Objects that survive many clean-ups get moved to a long-term store, just as trusted equipment is promoted to the permanent kit room.
Step-by-Step Explanation
Step 1
Allocate on the heap
New objects are created in the Young generation's Eden space.
Step 2
Determine reachability
The JVM marks objects reachable from GC roots — stack variables, static fields, and active threads.
Step 3
Minor GC
Unreachable young objects are collected; survivors move between survivor spaces and age.
Step 4
Promotion
Objects that survive enough minor collections are promoted to the Old generation.
Step 5
Major / Full GC
The Old generation is collected less often via mark-sweep-compact to reclaim long-lived garbage.
Step 6
Compaction
Live objects are moved together to remove fragmentation and speed up future allocation.
What Interviewer Expects
- That GC is based on reachability from GC roots, not reference counting
- Understanding of the generational heap (Young, Old, Eden, survivor spaces)
- The difference between minor and major/full GC
- Awareness of mark-sweep-compact and collectors like G1 or ZGC
- That System.gc() only suggests, and finalize() is unreliable/deprecated
- How memory leaks still happen via lingering references
Common Mistakes
- Claiming Java uses reference counting like older languages
- Believing System.gc() forces immediate collection
- Thinking garbage collection makes memory leaks impossible
- Confusing the stack with the heap for object storage
- Relying on finalize() for cleanup instead of try-with-resources
- Assuming setting a variable to null instantly frees memory
Best Answer (HR Friendly)
“Java automatically cleans up memory by finding objects your program can no longer reach and reclaiming their space, so you don't free memory by hand. It focuses on newly created objects first because most are short-lived, and moves long-surviving ones aside so the frequent clean-ups stay fast.”
Code Example
public class GcDemo {
public static void main(String[] args) {
String data = new String("heavy object");
// The object is reachable via 'data' here.
System.out.println(data.length());
// Dropping the last reference makes it unreachable
// and therefore eligible for garbage collection.
data = null;
// A hint only — the JVM decides when to actually collect.
System.gc();
System.out.println("Reference cleared; object is now eligible for GC");
}
}Follow-up Questions
- What are GC roots and how does reachability analysis work?
- Explain the difference between minor GC and full GC.
- How do G1, Parallel, and ZGC collectors differ?
- Why is finalize() deprecated and what replaces it?
- Can garbage collection still leave you with a memory leak? How?
- What is the difference between the stack and the heap in the JVM?
MCQ Practice
1. An object becomes eligible for garbage collection when:
The JVM collects objects that are unreachable from GC roots, regardless of scope details.
2. Where are newly created objects first allocated?
New objects start in Eden; survivors are later promoted to the Old generation.
3. What does calling System.gc() do?
System.gc() is only a hint; the JVM is free to ignore it or defer collection.
4. Which technique does the HotSpot JVM primarily rely on?
HotSpot uses reachability analysis with mark-sweep-compact style collection, not reference counting.
Flash Cards
What makes an object eligible for GC? — It is no longer reachable from any GC root.
What are the heap generations? — Young (Eden + survivor spaces) and Old — plus Metaspace for class data.
Minor vs major GC? — Minor collects the Young generation frequently; major/full collects the Old generation less often.
Does System.gc() force collection? — No — it is only a suggestion the JVM may ignore.
Can leaks still occur with GC? — Yes — objects kept reachable by unintended references (e.g. static collections) are never collected.
What is compaction? — Moving live objects together to remove fragmentation after sweeping.