File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Urgent......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 "Urgent......Garbage Collection" Watch "Urgent......Garbage Collection" New topic

Urgent......Garbage Collection

shashank hiwarkar1

Joined: Feb 11, 2001
Posts: 25
Can String literals ever be garbage Collected?

String s1="abc";
String s2="aaa";
When will be s1,s2 be garbage collected?

Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
If they are created on the heap they can get gc'd, if they are created in the Constant Pool they will not.
If they are resolved at compile time (like your examples) they will (probably) get created in the Constant Pool.
If they are created at runtime like
String s3 = s1+s2;
they will (probably) be created on the heap.
The reason for the disclaimer is that Sun does not really tell vendors how to implement the specifications. Some PHD student might create a very inefficient JVM that implements EVERYTHING on the heap (not a very good idea).

"JavaRanch, where the deer and the Certified play" - David O'Meara
Pratap Reddy
Ranch Hand

Joined: Jan 05, 2001
Posts: 36
Hi Shashank,
There is no way to find gc'd. Since they are stored on heap. Only objects which created on heap are gc'd. Or else all objects created with new keywords are gc'D.
I agree. Here's the link:
subject: Urgent......Garbage Collection
It's not a secret anymore!