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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With