☕ Java Beginner

What is garbage collection in Java?

Answer

Garbage collection (GC) is Java's automatic memory management mechanism that reclaims memory occupied by objects that are no longer reachable by any live reference in the program. Developers do not manually free memory (unlike C/C++), which eliminates memory leaks from forgetting to deallocate and dangling pointer errors. The JVM's garbage collector runs in the background, periodically identifying unreachable objects and freeing their memory. The primary GC regions are the heap (where objects live) and its generations: Young Generation (Eden + Survivors) and Old Generation. You cannot force GC, but System.gc() suggests it (the JVM may ignore it).