How does garbage collection work in Java?

Garbage Collection (GC) is an automatic memory management process in Java that identifies and removes objects that are no longer reachable or in use. This helps reclaim heap memory and reduces the risk of memory leaks.

Diagram: Young and Old Generation in garbage collection
Young and Old Generation in garbage collection

Key Points

Example

If an object is created and later all references to that object are removed, the object becomes eligible for garbage collection. The JVM can then reclaim its memory during a GC cycle.

public class Demo {
    public static void main(String[] args) {
        Demo obj = new Demo();
        obj = null; // Object becomes eligible for Garbage Collection
    }
}

Interview Tip

A concise interview answer is

Garbage Collection is a JVM process that automatically identifies and removes unused objects from heap memory. It helps manage memory efficiently, prevents memory leaks, and eliminates the need for manual memory management.

Last updated: 11 November 2026

Previous question: Which is faster to access, heap or stack, and why?

Next question: What is the role of the finalize() method in garbage collection?

More Core Java - Level II interview questions

All Core Java - Level II questions