An object becomes eligible for garbage collection when there is no reference pointing to it anymore.
In your example, you have created 3 objects inside the main method, but the code is passing the references between the reference variables.
Let's see your code in details:
At line 5, you create a new Person object and assign it to the reference variable elena (it is a local variable).
At line 6, you create another Person object and assign it to the reference variable diana (another local variable).
At line 7, you are passing the reference of the second object created (pointed by the variable diana) to the instance variable youngestChild of the object pointed by the variable elena. Now, you have two variables pointing to the same object.
At line 8 you are assigning null to the variable diana. This means that now diana points to null, and the object created at line 6 is only referenced by the instance variable youngestChild of elena (elena.youngestChild). Thus, the object still has a reference, and it won't be eligible for garbage collection yet.
At line 9, you are creating a new Person object, referenced by the reference variable zoe.
At line 10, you are assigning another reference to elena.youngestChild, so it will point to the same object pointed by the variable zoe. Now, remember that elena.youngestChild was pointing to the object created at line 6, and it was the only reference that was pointing to this object, since at line 8 you eliminated the other reference to the same object. This means that the object created at line 6 has no reference to it anymore, and after line 10, it will be eligible for garbage collection.
At line 11, you are assigning null to the variable zoe, but the object that was referenced by this variable is still being referenced by another variable (look at line 10 again), which means that it will not be eligible for garbage collection before the main() method ends.
Concluding, only the object created at line 6 will be eligible for garbage collection right before the main() method ends.
AngelinaJeana Brown wrote:Can someone explain how many objects are eligible for gc and when they become eligible?
When objects become eligible for Garbage Collection is one of the most popular (and sometimes hard to understand) topics in this forum, so if you use the search function you'll find plenty of (excellent) topics about this topic. Here are a few: