What You'll Learn
You'll learn when an object is considered reachable (alive) and when it becomes unreachable (eligible for cleanup).
Object Reachability Explained
An object is reachable if your program can access it through any active reference variable. Think of references as paths: as long as there's a path from your running code to an object, that object is reachable and stays in memory.
An object becomes unreachable when no reference variables point to it anymore. Once unreachable, the object is effectively lost to your program—you can't interact with it, and it's just taking up space on the heap.
The Analogy
Imagine objects as houses in a neighborhood. Reference variables are like roads connecting to those houses. If there's at least one road leading to a house, you can reach it (reachable). If all roads to a house disappear, you can't get there anymore (unreachable). The city eventually notices and clears away the abandoned house (garbage collection).
How Objects Become Unreachable
String message = new String("Hello"); // Object is reachable via 'message'
message = null; // Object is now unreachable
When message is set to null, the String object has no reference pointing to it—it's unreachable.
Person p1 = new Person("Alice");
Person p2 = p1; // Two references to same object
p1 = null; // Object still reachable via p2
p2 = null; // NOW the object is unreachable
An object stays reachable as long as at least one reference points to it.
Why This Matters
Understanding reachability helps you grasp memory management. Unreachable objects become eligible for garbage collection, freeing up heap space automatically. You don't have to manually delete objects—Java does it when they become unreachable.
Key Takeaway: An object is reachable if any active reference points to it; once all references are gone or reassigned, the object becomes unreachable and eligible for garbage collection.