This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Of course it represents the same value, But == operator checks the Bits (Memory location of a Object when comparing each other) there it results the false to compare actual value within a object you need to use equals() method
if(b1.toString().intern() == b1.toString().intern()) --> This will return true.
The intern function places the strings in the string constant pool rather than heap memory. I suggest for more concept on strings refer Beginning Java Objects.pdf.
Joined: Feb 28, 2007
Originally posted by Dean Jones: Hi Gitesh, the first time toString() is invoked, if it creates a String object, doesn't it go to the String Pool. So in the second time when it toString() is called, does a new object get created?
The toString() method creates a new object every time, if and only if it is invoked on an non-String type.
Had it been a string, toString() will place the object in the string pool.
I would appreciate if any Bartender would throw some more light on toString() keeping in mind the above discussion. That will be appreciated a lot.
.toString() method of Object was never designed as an API item for equivalence which is why Object includes the .equals() methods. All toString() is really useful for is giving developers / users interesting information about the internal state of the object. Do not attempt to discover any type of meaningful information from toString() unless you yourself designed the class for that purpose.