I am having a great deal of problems when I solve questions from garbage collections. In general the questions like, How many objects would be garbage collected. Is there any diagramatic way to solve such questions.
Yes, when you create a reference to a new object. Draw two boxes. One to for the stack, where the reference variable goes, and one for the heap where the Object instance goes. (Strings not included)
Then draw a line from the reference to the instance. This shows that the instance that is on the heap has a reference and is therefore not eligible for garbage collection yet.
If the instance creates new Objects then put that new object into the heap, but have the object atht is in the heap point to the new object in the heap.
So if you create another new object that the old reference variable will now point to, you will erase the previous line. When an object on the heap does not have a reference pointing to it from the stack, it is very possible that that is now eligible for garbage collection. The only time it won't be is if another object in the heap has a reference to that object, and some other reference from the stack points to that other object.
Islands are objects all on the heap that point to each other. As long as there is one reference, in the stack, that points to one of those objects in the heap, then all those heap objects that point to each other are still referenced and not eligible for garbage collection.