It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String literal GCed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String literal GCed?" Watch "String literal GCed?" New topic

String literal GCed?

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Hi all,
I read some where that String literal is never gc'ed.
Now String literals are created in the String constant that not a heap?
Can someone shed some light on this issue?
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391

At source code line 3, s1 refers to a String object. At line 4, s1 is set to null. Normally we would say the object is eligible for gc after line 4.

But byte code line 5 is loading the same reference as byte code line 0.
ldc is the byte code instruction to load a reference to an instance of class String representing a String literal. #2 is an index into the runtime constant pool (not String pool).
This is as close as I can come to proving that interned String objects are not garbage collected.
[ November 08, 2003: Message edited by: Marlene Miller ]
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Thanks Marlene.
GC combined with string literals can get tricky.
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
The good news is that "for the purpose of the exam" (sorry Marlene, it's the focus police again ), GC and the String pool won't be mixed together. When the exam asks you to determine how many objects are eligible for the GC, it won't be referring to String objects.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
I agree. Here's the link:
subject: String literal GCed?
It's not a secret anymore!