File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Is my thinking correct? 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 "Is my thinking correct?" Watch "Is my thinking correct?" New topic
Author

Is my thinking correct?

Santosh Bapat
Greenhorn

Joined: Mar 13, 2002
Posts: 7
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?


A sincere thanks to all those who take the time to help others.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Santosh
The subject of stoing literals and garbage collection has been raised at least a few million times.
Here is one thread with some info for you.

You can also try to
search for the answers.


Dave
alex earnshaw
Ranch Hand

Joined: Nov 05, 2001
Posts: 60
Originally posted by Santosh Bapat:
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?

To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex
Donald Yee
Greenhorn

Joined: Feb 22, 2002
Posts: 6
Originally posted by alex earnshaw:

To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex

I believe that since the code is using string literals, "Test" is never eligible for collection.
The string literal is placed into the pool and as such has something always referencing it.
Now if the code said:
String string1 = new String("Test");
String string2 = new String("Today");
string1 = null;
string1 = string2;
then, the first object is eligible when string1 is set to null.
Of course if I'm wrong someone will correct me
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is my thinking correct?