GuruKulki
GuruKulki

Reputation: 26418

Garbage collection and Strings

I have some doubts regarding Strings

Are they live on Heap or String pool?

And if on Heap then they will be garbage collected, if they are not reachable by any live thread.

And if on String pool then how they will be deleted or removed because as we know Garbage Collection happens only on heap.

Upvotes: 5

Views: 2467

Answers (3)

Vishal
Vishal

Reputation: 20617

String Alex goes into the literal pool, stays there as long as the process runs (or the web application remains loaded.) as told by finnw and is never garbage collected. String name2 doesn't allocate memory for "Alex" and reuses it from the literal pool.

PS: Literal pool is on the heap as well.

For string John two objects are created with reference name3 and name4 which are garbage collectible.

String name = "Alex";
String name2 = "Alex";

String name3 = new String("John");
String name4 = new String("John");

Upvotes: 1

Zacky112
Zacky112

Reputation: 8879

String s = new String("abc");

the string object referred by s will be on heap and the string literal "abc" will be in string pool. The objects in the string pool will not be garbage collected. They are there to be reused during the lifetime of the program, to improve the performance.

Upvotes: 8

finnw
finnw

Reputation: 48619

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).

Upvotes: 5

Related Questions