System.out.println("string" == "string"); //output: true System.out.println("string".toString() == "string"); //output: true System.out.println(" string ".trim() == "string"); //output: false So " string ".trim() returns a new String instance of "string" which is not the literal String instance "string"?
Hi, " string ".trim() constructs and returns a new string so the reference is not the same anymore ie. its a new object. You would get true in you used an equals() call instead in the 3rd line because its looking for the same value.
Since String objects are immutable, every method that tries to manipulate them will return a new String object. The implementation of the toString() method in the String class is a little special: it does not try to manipulate the String object, it just return the same object. FYI, the implementation is :
posted 18 years ago
Kevin, Another special case of String class as far as I know: System.out.println("STRING".toUpperCase() == "STRING");//true
Hi, The trim() method returns the reference to the same object if it does not need to be modified, that is it has no leading and trailing blanks. If the original String object needs to be changed then a reference to a new String object is returned. Hope this helps. Vani
Vani Kadur<br />==========<br />SCJP(98%)<br />SCWCD(85%)<br />IBM Certified Developer - XML and Related Technologies.