aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage collection 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" Watch "Garbage collection" New topic
Author

Garbage collection

Mathangi Shankar
Ranch Hand

Joined: Nov 01, 2004
Posts: 56
Hi,

At what stage in the following method does the object initially referenced by s becomes available for garbage collection.

void X() {
String r = new String("abc");
String s = new String("abc");//obj
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

The answer for this question is that theobject labelled 'obj'is garbage collected Before statement labeled 4.

Please anyone explain me the solution of the above code.

Mathangi....


--------------------------------<br />SCJP1.4
Abdulla Mamuwala
Ranch Hand

Joined: Jan 09, 2004
Posts: 225
Hi Shankar

A object is garbage collected when all live threads loose a reference to that object. One way to make a object eligible for garbage collection is by assigning it a null value,
Object obj=null
In the code you have provided the object s is never assigned a null value nor does it it form a isolated island of objects.
Therefore according to me the object should not be garbage collected before statement labeled 4.
Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
void X() {
String r = new String("abc");
String s = new String("abc");//obj
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

At line 3, the object originally held in s ("abc") is reassigned, so s points to a String with the value "abc abc".
So, after line 3 (and before line 4), the object originally held in s is eligible for garbage collection.
[ March 11, 2005: Message edited by: Kedar Dravid ]
Ravi Raj
Greenhorn

Joined: Feb 02, 2004
Posts: 1
's' does not have "abc abc". it would have "abcnull". can someone explain how it is eligible for gc.

RR
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
String "abcnull" is a new object. When s refers to "abcnull", it no longer refers to the "abc" string created in line "obj", so that object is eligible for gc right after line 3.


Mike Gershman
SCJP 1.4, SCWCD in process
Mathangi Shankar
Ranch Hand

Joined: Nov 01, 2004
Posts: 56
Hi Mike,

Thanks for the solution.

Mathangi.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage collection