Since this is posted in Beginner, a warning to any beginners who read this
thread: stuff about the String pool and garbage collection really, really, really does not matter most of the time. You can waste a lot of time trying to understand this, but if you're indeed a beginner, there are many other things that would be more worthwhile to spend time on.
But if you're still here, what the heck...
[Vijay]: So, only if we explicitely call the garbage collector, the string literals/constants will be garbage collected. Am I right? No.
If the String objects referenced by String literals do become eligible for GC, then that can happen whether or not System.gc() is called. Calling System.gc() makes collection considerably more
likely, but nothing will happen during gc() that wasn't already
possible without gc().
So when exactly is it possible for a String refenced by a literal to be GC'ed? Only if the class that referenced the literal is itself GC'ed. Which in turn is only possible if the class loader that loaded that class is GC'ed.
If these two things happen,
and there are no additional references to the String, then it's eligible for GC. The intern pool (the one described in the API for String's intern() method) does not prevent GC - it behaves like a weak reference. However the reference held by the Class is a hard reference, as is the reference held by the ClassLoader to each Class it loaded. So you can ignore the intern pool when thinking about GC of strings, but you can't ignore Classes and ClassLoaders.
What this means is that Strings referenced by String literals
can be GC'ed, but it's pretty rare -
unless either you're intentionally mucking around with different class loaders, or you're in an environment which routinely creates and discards class loaders
for you. (Like say, an application server, or some IDEs I believe.)
[ December 05, 2005: Message edited by: Jim Yingst ]