This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I understand that String objects are immutable, so these when you apply these methods to a String object, a new String object is returned. Above, both the substring() and trim() should return "String". So, why do they give different results when compared to "String"?
Sun Certified Java Programmer 1.5,
Sun Certified Web Component Developer 5.
"No pain. No Gain"
Since Strings are immutable....performing trim() on " String " would not affect the original string(i.e. " String "). Therefore you are comparing " String " with "String"...which is obviously FALSE.
No. " String ".trim() is equal to "String", so the two strings have the same value. But the trim operation creation a new String object, and since "==" test for object equality -not string equality- the result is false. [ May 13, 2008: Message edited by: Ulf Dittmer ]
* 'new' operator ALWAYS creates an object on heap. * All methods in String class which return a string (toUpperCase(), toLowerCase(), trim() etc.) create the new object on heap, ONLY if required. If not required (say there are no white-spaces to trim), the same instance is returned.