jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Objects" Watch "Objects" New topic


Paul Keohan
Ranch Hand

Joined: Mar 15, 2000
Posts: 411
The following code changes the value of a StringBuffer :

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.
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

keep in mind that Strings are immutable, and StringBuffers are mutable. So... when you call s.trim() it actually returns a reference to the new String it created that has the trimmed whitespace:

You can search for more info on this mutable and immutable in the Programmer's Certification Study forum.
[ June 10, 2002: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
Ok Jessica ... it seems quite interesting and confusing..Yes Strings are immutable..and I was thnking if this is the case than perhaps in
String x = " test ";
x = x.trim();
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:
String x = " test ";
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?
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Objects
It's not a secret anymore!