Course contentsShow
← Java
Lesson 298 of 2,8707. Reference Types and Object FundamentalsFree lesson

Garbage Collection Overview

How the JVM automatically reclaims memory from unreachable objects without explicit programmer intervention.

Garbage Collection Overview

What you'll learn: How Java automatically frees memory from objects you're no longer using, so you never have to manually delete them.

What Is Garbage Collection?

In Java, you create objects with the new keyword, and they live on the heap. But what happens when you're done with them? Unlike languages like C or C++, where you must explicitly free memory, Java handles cleanup for you through garbage collection (GC).

Garbage collection is the JVM's automatic process of finding objects that are no longer reachable (meaning no reference variables point to them) and reclaiming their memory. Once an object becomes unreachable, it's eligible for garbage collection—the JVM will eventually destroy it and free its memory for reuse.

How It Works

Remember object reachability? If no active reference points to an object, that object cannot be accessed by your program anymore. The garbage collector periodically scans the heap, identifies these unreachable objects, and removes them.

You don't control when garbage collection runs—the JVM decides based on memory pressure and internal algorithms. You simply stop using objects (by setting references to null, letting them go out of scope, or reassigning them), and the JVM takes care of the rest.

Think of It Like This

Imagine a parking lot (the heap) where you park cars (objects). When you leave your car and walk away without keeping your parking ticket (reference), the lot manager eventually notices abandoned cars and tows them away to make room for new vehicles. You never have to call a tow truck yourself—it's automatic.

Key Takeaway:
Garbage collection automatically reclaims memory from unreachable objects, freeing you from manual memory management and preventing memory leaks.