The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


RE:Array default initilization

Posted by Kishori Sharan on January 23, 2001 at 10:44 AM

Hi Suchak
In first case
Array a = { new XYZ("sss"),new XYZ("sss1"),new XYZ("sss2"));

Java creates an object named on heap ( which is the array name ) which has three pointers ( I am talking how JVM implements it ). Then, it creates three objects on heap like new XYZ("sss") and so on. Each pointer in the first object points to one object on heap e.g. the first pointer will point to the object new XYZ("sss") and second to new XYZ("sss1") and so on. Finally, the refernece variable a ( as indicated by you in Array a) points to the array object on heap itself. So now you have four objects on heap, 1) array itself, 2) three object which you used to initailize the array. The refernce link is a -> to array --> each object (3 object here ) . If you set a = null then the first refernce link a - > array is broken. Now when garbage collector looks at array object then it sees there noone refers to this object , so it can be garbage collected and since array itself can be garbage collected, so can be other three objects. So setting a = null makes all four objects on heap a candidate for garbage collection, unless all ( or some ) the three objects makes themself reachable in their finalize method.
However, when you create an array like
int[] a = { 1, 2,3 } ;
then JVM creates only one object on heap which holds all the three values and reference variable a refers to that object on heap. So in this case a = null will allow garbage collector to do the final rituals for that one and the only one existing array onject on heap.
In the first case I assumed that you are not storing the reference of three object e.g. new XYZ ("sss") in any reference variables other than the array itself. Suppose, after creating the array if you do something like
XYZ x = a[0] ;
so even if you say a = null, the first of three objects on heap won't get garbage collected since there is a valid reference to that object.However, the other two would be get garbage collected.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us