== does reference equality. even though " String ".trim() yeilds you the literal value "String" ; it doesn't reference the same object as "String". This is because " String ".trim() give the result at run time and for the strings to be interned it has to be the same value at compile time. Hope this helps
author and iconoclast
That's a pretty good explanation, but it's unfortunately incorrect; the code will print "Equals". This happens because trim() is smart enough to return its argument if it's unchanged, rather than a copy of the argument; this is documented in the Javadoc for the trim() method.
Joined: May 25, 2005
your answer is correct and I understand your explanation too. So, the same explanation shoule be applicable for this code also, correct?
Interesting. It looks like EFH gave an incorrect answer because he didn't notice the spaces in " String " in the original code. (Chitra, please use [code] tags in the future to make your code easier to read.) However now that Chitra has asked, effectively, what happens if we remove the spaces to get "String" - now EFH's answer is correct for the new question. So congratulations, EFH, for psychically sensing a question from the future, and answering it correctly.
Hi Chitra, If u put " string " with spaces at both ends or a space at either end, the method will create a new string. But if u put like this "string" with no spaces in the end, it will return the same string, which is already in the string pool. That is why it prints "equals". If u have any doubt in string methods, it is better to have a look at the source code.
Hi Friends. I was just following this String Class duscussion here. Can someone explain me why the following code produces an output "Equal". I think it should be "Not Equal" cause both "String" declarations create two different objects. while the tostring() on the first "String" object returns back the same "String" object still its different then the actual second "String" object.
[ June 01, 2005: Message edited by: Ashok Golani ]
Why do you think the two "String" declarations create two different objects? That is just the opposite of what the spec says. Both "String"'s are compile time constants and will be placed once into the String pool, so they will be the same object.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
so after getting trimed...the new "String" object is actually the one already inside the String pool.so they both contain the same bitpattern refering to the same address on the heap.