This is the question from whizlab :
How many objects are eligible for garbage collection when the System.gc() method invoked?
options are
A. 3
B. 4
C. 5
D.None of above.
Answer is A
How??
I think when we assign null reference to array object all objects are eligible for gc, since all MyClass object in array will be in Island of isolation(gc).
You will find that the last array position still holds the MyClass object. Also, the reference to array is not changed from the caller's perspective.
array[0] = X; is an assignment operation that will work to change the contents of this array. However array=null will not assign the reference to null outside this method's body. The caller still holds the reference to the array
rohan yadav wrote:Then, what array=null means in above example?
And how many objects are eligible for garbage collection
array=null only modifies the local array in method f. It doesn't effect the original array in main method. Thus 3 objects are eligible for GC i.e. array[0], array[1] and array[2]...
dude see.....when you passed the array to the method you create a new variable that contains the position of the array....so this refers to the original array.....but mind you this is a new variable that refers to the same array.... when you null this reference the object is still being referred by the original variable....so it not available for gc....
but using the new ref variable in the method you change the contents of the array....that is you make array[0], [1],[2] null....so objects referred by them become available for gc...
Thanks Ankit and Ankur, understood. Now i am ready for any question regarding passing object reference to methods.
Special thanks to Ankit, the link you provided was awesome.