Objects are never static, references are static. As you said before, if in method m2, some code like this is present:
q3[index++] = q1,
where q3 is either an instance variable(of an instance that is not eligible for gc) or a static variable(if the classloader is not eligible for gc). index is again a static integer. In this case, none of the objects will be eligible for gc.
However, if the code is as follows:
q3 = q1
Then 9 objects will be eligible for garbage collection as the above code will only hold on the last object created. Hope it is clear.
Originally posted by suresh mulagala: what if m2 is setting q1 to null ? by the time it gets to the sytem.out, all of them would have been de-referenced and eligible to GC so in that case will not be holding on to any...
This is the most common mistake i have seen people make. Even if you set q1 = null inside m2, its a different variable reference you are pointing to null, the variable q1 in m1 method will still point to the last created object.
Originally posted by suresh mulagala:
Another case: if there were static fields in the class and m2 is setting them to static fields none of them will be eligible to GC as they all have living references.....am i right?
This is what i meant when i said there is an array of references (case 1 in my comment). But ofcourse this is a valid case where a class has as many different references as the number of objects created in the loop! People usually use arrays or other data structures for such a scenario.