Tuesday 24 October 2017

What is String pool in 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.


itemprop="text">
class="normal">Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...