Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is String pool in Java? [duplicate]

Tags:

java

I am confused about StringPool in Java. I came across this while reading the String chapter in Java. Please help me understand, in layman terms, what StringPool actually does.

like image 597
Subhransu Mishra Avatar asked Sep 27 '10 05:09

Subhransu Mishra


People also ask

Can string pool have duplicate values?

no if you will use new in any situation a new object will b created even if there is another string with the same value present in string pool.

What is the string pool in Java?

String pool is nothing but a storage area in Java heap where string literals stores. It is also known as String Intern Pool or String Constant Pool. It is just like object allocation. By default, it is empty and privately maintained by the Java String class.

What is the difference between string pool and heap?

The Java string constant pool is an area in heap memory where Java stores literal string values. The heap is an area of memory used for run-time operations.

Is string pool part of heap?

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.


1 Answers

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";     String t = "ab" + "c";     System.out.println(s == t); 

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

like image 90
Nikita Rybak Avatar answered Sep 19 '22 23:09

Nikita Rybak