I think it becuase when you are comparing a string using == operator, using this operator Java will compare the reference address of those strings. If you want to compare their contents use String.equals() method instead.
[ October 17, 2005: Message edited by: Ken Blair ]
I agree that your last example is bad, but it is entirely predictable if you understand how == works with String objects. In this case, the condition of the if statement evaluates to true because you are using String literals here. If you want to know more, you should google for "String Constant Pool" or something along those lines.
The first thing to do is to check the API for String - do not trust your intuition or "feeling". You will read in the API for the trim method that " XXXXXXX ".trim() returns a new String object. Although the String object will contain the characters XXXXXXX, it does not say that the new String object will be the same as one previously defined as a String literal as in "XXXXXXX" or as a previously interned String containing those characters. So a "==" comparison will evaluate to false.
You may use the intern method of the String class to enter a string into the pool: