wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes garbage collection doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "garbage collection doubt" Watch "garbage collection doubt" New topic
Author

garbage collection doubt

sunitha thejaswi
Ranch Hand

Joined: Nov 14, 2005
Posts: 31
please explain the answer of this question

class I {
private String name;
public String toString() {return name;}
public I(String s) {name = s;}
}
class J {
private static void m1(I[] a1) {a1 = null;}
public static void main (String[] args) {
I[] a1 = new I[3]; // 1
a1[0] = new I("A"); // 2
a1[1] = new I("B"); // 3
a1[2] = new I("C"); // 4
m1(a1);
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i]);
}}}

After method m1 returns, the object created on which line is eligible for garbage collection?
a. 1
b. 2
c. 3
d. 4
e. Compile-time error
f. Run-time error
g. None of the above


answer is g:none of the above

when array a1 is passed to method m1 refrence to array object a1 is passed.
Then when reference of a1 is made null why doesn't it reflect in the calling method.
why is it not ready for garbage collection.

please explain..
Thank you,
sunitha
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

The a1 inside the method m1() is *not* the same variable as the a1 in the main() method; it's a copy. You set the copied variable to the null reference in m1(), but the a1 reference in main() still points to the array object. Since a reference is retained, the array is not eligible for GC. As the array retains references to the I objects that get created, they're not eligible, either.

Hope this helps.
Lakshmanan Arunachalam
Ranch Hand

Joined: Nov 02, 2005
Posts: 99

when array a1 is passed to method m1 refrence to array object a1 is passed.


Small change in the above statement,

when array a1 is passed to method m1, it means "the value of reference variable" a1 is passed. i.e a variable whose value is copied from a1 referene. Hence if you change the value of that variable inside method m1, it wont affect the array a1


Regards<br />Lakshmanan<br />IBM-OOAD & UML, SCEA-I
sunitha thejaswi
Ranch Hand

Joined: Nov 14, 2005
Posts: 31
thank you now i get the point
 
Don't get me started about those stupid light bulbs.
 
subject: garbage collection doubt
 
Similar Threads
Doubt in GC
Garbage Collection II
Garbage Collection
Garbage Collection
Dan exam doubt 19