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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This prints
true(even though we don’t useequalsmethod: correct way to compare strings)When compiler optimizes your string literals, it sees that both
sandthave same value and thus you need only one string object. It’s safe becauseStringis immutable in Java.As result, both
sandtpoint 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
Stringobject compiler checks if such string is already defined.