This will print 'textmore text'. But if I do a similar thing with a String object, the value doesn't change. For example :
s will still print out surrounded by spaces. I'm assuming that the reason for this is the same reason that makes any other object equal to sb change at the same time that you change sb. Whereas, changing the value of s will not change the value of any object that was set equal to it. Thanks!
Ok Jessica ... it seems quite interesting and confusing..Yes Strings are immutable..and I was thnking if this is the case than perhaps in case1: ******** String x = " test "; x = x.trim(); System.out.println(x); will print the test without spaces...what I am assuming that : 1. in first step it is acually doing String x = new String(" test "); 2. In second step it reassigning the value ..that is Ok as in immutable I can't change but reassign the things. 3. And in third step my Sytem print is printing the trimmed value. But in second case: case2: ***** String x = " test "; System.out.println(x.trim()); why it is trimming the value? I am not reassinging and if it is immutable than it can't altered this? One of collegue has an idea that when you do System println it actually works in Stringbuffer in background and converts back to String using toString() method... is it so? if not how the JVM is alterring the value? regards, Arun
hi in your second case your printing the return value of the trim() method which is of type String. so String x = " * " creates a String, and x.trim() returns a copy of this string with whitespaces ommitted. in your println statement you do not assign the return value (you cannot access it outside of the println statement). here is what javadoc says: 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. p