Sunday 7 January 2018

Why are equal java strings taking the same address?













I
was playing around with Strings to understand them more and I noticed something that I
can't explain :



String str1 =
"whatever";
String str2 = str1;
String str3 =
"whatever";
System.out.println(str1==str2); //prints true...that's normal,
they point to the same object
System.out.println(str1==str3); //gives
true..how's that possible
?



How is
the last line giving true ? this means that both str1 and str3 have the same address in
memory.



Is this a compiler optimization that was
smart enough to detect that both string literals are the same ("whatever") and thus
assigned str1 and str3 to the same object ? Or am I missing something in the underlying
mechanics of strings ?


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



href="http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3">http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3



As
the post says:





String allocation, like all object allocation, proves costly in both time and
memory. The JVM performs some trickery while instantiating string literals to increase
performance and decrease memory overhead. To cut down the number of String objects
created in the JVM, the String class keeps a pool of strings. Each time your code create
a string literal, the JVM checks the string literal pool first. If the string already
exists in the pool, a reference to the pooled instance returns. If the string does not
exist in the pool, a new String object instantiates, then is placed in the
pool.





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