It is always better to use equals method than '==' for string comparison.
The equals() method checks whether two strings have the same characters, whereas the == operator checks if two operands refer to the same String object. '== ' tests to see if the references in the variables point to the same memory address.
== operator will give false when the two comparing operands are of different objects. so == will return true when the operands refer to the same object.
in the first sinppet " String ".trim() will create a new string object and when that is compared to the second operand "String" it will return false.
in the second snippet "String".trim() operation will not create a new string object since the "String" object is already trimmed so the old object is retained. and when that is compared with "String" it returns true. the same thing applies to snippet three also.
Snippet 1: In this case the trim() method will create new String object. This new object is equal to "String" according to equals() method. But this is not equals to "String" according to ==, because both are entirely different objects.
Snippet 2: Here, there are actually no spaces to trim in "String". So, if you see the source code for trim() method you will see that it will return this object when there are no spaces to trim. That's why they both are equal according to ==
Snippet 3: Same case here too. The toString() in String class always returns this object. [ December 20, 2005: Message edited by: Ravisekhar Kovuru ]
straws are for suckers. tiny ads are for attractive people.
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop