Hi, Could anyone please explain why the first statement is true and rest are false. "String" == "String".trim() // is true "String" == "String ".trim() // is false "String " == "String ".trim() // is also false "String ".trim() == "String ".trim() //also false Thanks a lot. Cheers!~ Sumit
Because any mutator method of class String (e.g. trim()) that changes the character pattern of a string, returns a new reference to a new string literal. Thus, the == comparison yields false. But, if the mutator method has no effect on the string literal, the same reference is returned. "String" == "String".trim() // is true trim() has no effect on "String", thus, the same reference is returned and the comparison yields true. "String" == "String ".trim() // is false "String " == "String ".trim() // is also false "String ".trim() == "String ".trim() //also false trim() has the effect of removing the last space character and a new reference to a new "String" literal is returned, thus the == comparison yields false. Bottom line, == compares the references and not the content of a string. Use equals() to compare the content.
Whenever in doubt, it helps to check the source code of some J2SE classes. For instance, if we have a quick look at the String.trim() method:
On the last line, we can see that either "this" is returned when no change occured or substring is invoked if some change is required. Looking at substring, we can see that it "Returns a new string that is a substring of this string" (from the API), thus the returned string is a new reference...
String variables are such a trap for even experienced java programmers. normally any method that acts on a string will return a new reference - I was totally unaware that some returned the "this" pointer. is there a list of which functions do this? (i'm assuming any method of String that returns a string... but who knows?) this would be very handy to know.
use the [CODE] tags - it makes it much easier for people to help you.
Check out the source of the String class. Basically, if a method does not mutate the String object, the same reference (i.e. this) is returned. For instance, the toString() method returns this. But, the substring() method could also return this only if the returned substring is the same as the one on which the method is invoked: String s = "String"; String t = s.substring(0); System.out.println(s==t); // prints true !!! [ July 23, 2002: Message edited by: Valentin Crettaz ]
My Linked In
Are you okay? You look a little big. Maybe this tiny ad will help: