This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I read in sierra bate book that to make java more memory efficient,String uses String constant pool that means it will create a single object for two different
references h1 and h2 . so,h1==h2 should return true. but unexpectedly jvm gives false.......why???
I am also confused about the output of line2 and line3 also.so,please explain me this also.
Thanks for reading my post,
Its because concat() method creates a new String object by calling one of String class constructors, and you know that if a String is created by calling a constructor then
its not taken from the String literal pool. This explains the output of the above program.
See the source code of String class, and check the concat() method.
The string objects h1 = h1.concat("world"), and h2 = h2.concat("world") are not pulled from the literal pool as they create new string objects. Thats why you have an output as false. Of course, all these string objects are on the heap, just the reference to the literal pool is not there.
But even if we don't use concat() but the + operator:
The result is still
But if we replace
then the result is:
gives true true true true).
I think as inh1 is calculated at runtime a new string is generated.
In h1 is calculated by using a string constant expression. In this case using + means the constant from the pool is taken, using concat() means a new string is generated.