DEV Community

Sharath Kumar
Sharath Kumar

Posted on

What is Garbage Collection?

Garbage Collection (GC) in Java is the automatic memory management process used by the JVM to remove unused objects from memory.

In simple terms:

👉 Garbage Collection frees heap memory by deleting objects that are no longer being used by the program.


✅ Why Garbage Collection is Needed

When a Java program creates objects, they are stored in Heap Memory.
If unused objects are not removed, memory becomes full and the application may crash.

Garbage Collector:

  • Identifies unused objects
  • Removes them automatically
  • Reclaims memory for new objects

✅ What is Garbage?

An object becomes garbage when:

  • It has no reference variable pointing to it.

Example:

class Test {
    public static void main(String[] args) {
        Test t1 = new Test();
        t1 = null;   // object becomes eligible for GC
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, the object created earlier has no reference → eligible for garbage collection.


✅ How Garbage Collection Works

  1. JVM creates objects in Heap memory.
  2. JVM tracks object references.
  3. Objects without references are marked as garbage.
  4. Garbage Collector removes them.
  5. Memory is reused.

✅ Types of Garbage Collectors (Conceptual)

  • Serial GC – Single-threaded, small applications.
  • Parallel GC – Multiple threads, better performance.
  • G1 (Garbage First) GC – Modern default collector, optimized for large memory.

✅ Ways to Make Objects Eligible for GC

  • Assign reference to null
  • Reassign reference variable
  • Object created inside method (after method ends)
  • Anonymous objects

✅ Important Interview Points

  • Garbage Collection works only on Heap Memory.
  • It is automatic (developer cannot force it).
  • System.gc() only requests, not guarantees GC execution.
  • Helps prevent memory leaks.

Top comments (0)