public static void main(String agrs[]){ MyClass[] array = new MyClass[4]; for (int i=0; i<array.length;i++) array[i]=new MyClass(); f(array); System.gc(); }
}//end class
correct answer is 3 whereas i feel it should be 4( the objects at line 1,2,3 and 4). In the method f() 3 out of 4 elements are made null and the array refernce itself is made null (at line4) then how come only 3 objects are eligible for GC.
thanks, Sarika.
Jason Kim
Greenhorn
Joined: Apr 13, 2003
Posts: 17
posted
0
That's because Java is 'pass-by-value' NOT 'pass-by-reference'.
When array variable main() is passed into method f(), a new local array variable is created. They point to same array but are two different reference variables.
Hence doing array = null in f() will only change what local array variable points to and does not change the array variable in main().
Hope this helps.
Sarikaa Bhatnagar
Greenhorn
Joined: May 10, 2005
Posts: 26
posted
0
HI,
this is exactly what i understand and this is what is causing confusion. When a copy of array is passed to f() then i believe there are totol 5 objects. 1 array reference itself and 4 its internal objects. Now when 3 objecs and the array ref itself is set to null - that makes the count 4 for objects eligible for collection.
I understand that the main() array is still there and still pointing to the original array.
Please explain!
Jason Kim
Greenhorn
Joined: Apr 13, 2003
Posts: 17
posted
0
Originally posted by Sarikaa Bhatnagar: HI,
this is exactly what i understand and this is what is causing confusion. When a copy of array is passed to f() then i believe there are totol 5 objects.
Please explain!
Sorry maybe I wasn't clear enough.
The whole array does NOT get copied across. It's only a reference variable that is getting copied. So there is only ever one array existing and this is created in main().
The array variable arrayVar is only a reference or handle to the array object. The variable contains some sort of address that identifies where the actual array exist in memory.
Hope this helps.
ravi satti
Greenhorn
Joined: Oct 16, 2007
Posts: 13
posted
0
In main method we have created totally 5 objects. 1 array object and 4 MyClass objects. After the call to f(array);, 3 of the MyClass objects doesn't have any reference. Only two objects have references. The array object itself(through the reference 'array') and one MyClass object(through the reference 'array[3]'). So those 3 objects will be (eligible for) garbage collected after the call to f(array);.