They are all stored in the heap, but intern()
ed strings (including string literals in the source) are referenced from a pool in the String
class.
If they appear as literals in the source code, including constant string expressions (e.g. "a" + "b"
) then they will also be referenced from the Class
the appear in, which usually means they will last as long as the process runs.
Edit:
When you call intern()
on a string in your code it is also added to this pool, but because it uses weak references the string can still be garbage collected if it is no longer in use.
See also:
interned Strings : Java Glossary
Quote from that article:
The collection of Strings registered in this HashMap is sometimes called the String pool. However, they are ordinary Objects and live on the heap just like any other (perhaps in an optimised way since interned Strings tend to be long lived).