First, I think there's a typo: The first example prints "Equal" and the second prints "Not Equal."
The question here is whether the method returns a
new String.
Note the API documentation for the trim method, which says it returns "A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space."
In the first case, "String" has no leading or trailing white space, so "String".trim() returns a reference to the original String without creating anything new. Also, because this is a String
literal, both occurrences of "String" reference the same object, and therefore "String".trim() == "String".trim() returns true.
In the second case, " String " requires trimming, and so a new String is created. Because this is a
new String, it is not referencing the same object as the literal. Therefore, " String ".trim() == "String" returns false.
In the third case, the replace method also returns
new Strings, and so the comparison returns false.
(Related topic:
Strings Literally.)
[ June 18, 2007: Message edited by: marc weber ]