• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer / StringBuilder methods

 
Tiju Thomas
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do StringBuffer / StringBuilder methods return a new StringBuffer / StringBuilder object? Is it not enough for the methods to do manipulation on the same object?

In case of String, it is ok as we will not be able to modify the same object. But why in StringBuffer / StringBuilder? Is there any practical use?
 
Sid Murrey
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does not return a new object. If you read the Java6 API documentation, you see that the methods return "this object" or "a reference to this object".
Thus,
<blockquote>code:
<pre name="code" class="core">StringBuffer sb2 = sb.append("blah");</pre>
</blockquote>
does not create a new object, but rather both reference variables 'sb' and 'sb2' point to the same StringBuffer object on the heap.
 
Tiju Thomas
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

But why should it be returned at all? We will be anyway invoking the dot operator on a specific StringBuffer / StringBuilder object from where the call is made. Is there any meaning in getting a new reference variable referring to the same object there?
 
Sid Murrey
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tiju, I don't really know for sure, but my guess would be that it is just for convenience.

Compare:
<blockquote>code:
<pre name="code" class="core">
public StringBuffer doStuff(StringBuffer sb) {
// do stuff
sb.append("blah");
return sb;
}
</pre>
</blockquote>

<blockquote>code:
<pre name="code" class="core">
public StringBuffer doStuff(StringBuffer sb) {
// do stuff
return sb.append("blah");
}
</pre>
</blockquote>
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's also useful if you want to chain method calls:

<blockquote>code:
<pre name="code" class="core">
String s = new StringBuilder()
.append("this")
.append("that")
.append("the other")
.reverse()
.toString();
</pre>
</blockquote>
 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

There are insert and delete methods in StringBuffer and StringBuilder classes through which you can modify these objects and as all other said one can also append string there.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic