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.

Key Points: • Garbage Collection is performed automatically by the JVM. • It removes objects that are no longer referenced by any active part of the application. • Reclaimed memory is made available for creating new objects. • Garbage Collection primarily works on Heap Memory where objects are stored. • Developers do not need to manually allocate or deallocate memory as in languages like C or C++.

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.

Code Example:

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."