What is garbage collection in Java?

Garbage Collection (GC) is an automatic memory management process in Java that identifies and removes objects that are no longer reachable by the application. This allows the JVM to reclaim memory and reuse it for new objects.

Key Points: • Garbage Collection automatically frees memory occupied by unused objects. • It helps prevent memory leaks and reduces the need for manual memory management. • The JVM periodically checks for objects that are no longer referenced and makes them eligible for collection. • Garbage Collection primarily works on Heap Memory where objects are stored. • Different GC algorithms such as G1 GC, Parallel GC, and ZGC are available to optimize performance.

Example: If an object is created and later loses all references pointing to it, the JVM can reclaim its memory through Garbage Collection.

Code Example:

public class Demo {

    public static void main(String[] args) {

        String str = new String("Java");

str = null; // Object becomes eligible for Garbage Collection

    }
}

Interview Tip: A concise interview answer is:

"Garbage Collection is an automatic JVM process that removes objects that are no longer reachable by the application. It helps manage memory efficiently, prevents memory leaks, and eliminates the need for manual memory deallocation."