|
An object is considered as unreachable when there is no reference, not a single one pointing to it. Whenever you want to make a particular object eligible for garbage collection, you have to make sure that all of its references point to somewhere else.
Nullify all references to the object.
You can explicitly make an object’s reference null. Then the object reference does not point to the object anymore. If all the object references are made null, the object becomes unreachable. Listing 6.1 creates a Car object and assigns two references to it.
![]() |
You can see from the listing that the Car object becomes eligible for garbage collection only after both the references to it are made null. When beetle is made null, you can still access the Car object with another reference, bug. Hence the object is reachable. But when bug is also made null, the Car object is unreachable and therefore is eligible for garbage collection.
Reassign object’s reference to some other object
An object can become unreachable if its sole reference is assigned to point some other object. We have already seen an example of this in section 6.2. In listing 6.2 two Car objects are created. The first Car object’s only reference, beetle, is reassigned to point to the second Car object.

The first Car object (“Beetle”) becomes unreachable after its sole reference, beetle, is reassigned. Note that object could be reachable even after one of its references is reassigned. For instance, in the following code, the Car object created on line 4 is accessible even after line 6 is executed.
4. Car beetle = new Car(“Beetle”);
5. Car funcar = beetle;
6. beetle = new Car();
After execution of line 5, the Car object created in first line has two references, beetle and funcar. At line 6, one of the references beetle is reassigned, but there is still one reference, funcar which points this Car object. Therefore, it is reachable and hence is not eligible for garbage collection yet.
In the examples we have discussed so far, we have seen the object references, which are stored on the stack because they were local variables. However, an object itself can store an object reference as one of its members. Since objects are created on heap, the member object reference is not stored on the stack. The object referenced by member reference is reachable only when the object of the member variable itself is reachable. In the next section, we will see the example of such objects.