wood burning stoves 2.0*
The moose likes Java in General and the fly likes StringBuffer [why this return?] append([implicit this]) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "StringBuffer [why this return?] append([implicit this]) " Watch "StringBuffer [why this return?] append([implicit this]) " New topic
Author

StringBuffer [why this return?] append([implicit this])

Guennadiy VANIN
Ranch Hand

Joined: Aug 30, 2001
Posts: 898
Why mutable StringBuffer instance in its methods, altering the same this object (like append(), insert(), etc.), have StringBuffer return(ed)?
All instance methods already have implicit reference to "this" instance
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Just so you can say
sb.append("blah").append("foo").append("bar");
Which is arguably more readable than
sb.append("blah");
sb.append("foo");
sb.append("bar");
And a good deal more efficient than
sb.append("blah" + "foo" + "bar");
Because the latter needlessly creates a temporary StringBuffer and String. It is amusing (or saddening) how often you see developers use the latter idiom.
- Peter
Guennadiy VANIN
Ranch Hand

Joined: Aug 30, 2001
Posts: 898
That was fast. Thanks. I understood that return is a copy of reference to StringBuffer instance
Guennadiy VANIN
Ranch Hand

Joined: Aug 30, 2001
Posts: 898
Peter.
cool! I asked before posting and after posting here a lot of programmers/developers in Java. Nobody could figure out
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 984

I still don't understand the original question. (But I think I understand the answer.)


Please ignore post, I have no idea what I am talking about.
Guennadiy VANIN
Ranch Hand

Joined: Aug 30, 2001
Posts: 898
Cristopher,
why, having understood answer, you could not understand qs.
Credits to Peter den Haan!!!
Anyway it is even more important (than receiving answer to specific technical qs) to be clear, and to be understood.
The questions was:
Why StringBuffer's methods, changing the same obj (not same as in case of String's methods), have returns of type StringBuffer but not of type void or boolean? I even could give counter-examples for similar circumstances...
Give me a word what should I correct more.
[This message has been edited by G Vanin (edited October 24, 2001).]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: StringBuffer [why this return?] append([implicit this])
 
Similar Threads
Need String program
garbage collection
StringBuffer class
Guess the answer
null