Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java StringBuilder append() return?

Tags:

java

string

oop

I'm just new in Java programming and it's really confusing me that what's the return type of method append() in StringBuilder??

I've checked about the API documents on https://docs.oracle.com/javase/9/docs/api/index.html?java/lang/String.html and the return is "StringBuilder", so I should write the code like:

StringBuilder a=new StringBuilder("hello");
...(another StringBuilder object)=a.append("world");

and a will still be "hello", and another stringbuilder will become"helloworld" because it has a return value??

But actually a itself also become "helloworld". Why??Did I misunderstand something?

like image 446
kevinHuang Avatar asked Sep 06 '26 05:09

kevinHuang


2 Answers

It is reasonable that StringBuilder follows the Builder Pattern, as it is used for building a String.

In a builder pattern each method (mostly) returns the current instance so that the return is a modified instance.

But actually a itself also become "helloworld". Why??

Because you are using the same instance to append again., so it already stored the previous value and was given the updated instance.

so I should write the code like:

StringBuilder a=new StringBuilder("hello"); ...(another StringBuilder object)=a.append("world");

You need not to. Since that returning the instance you can chain your method calls. That is the beauty of builder pattern.

StringBuilder a=new StringBuilder("hello");
a.append("World").append(" Mr.").append("Blah");
like image 105
Suresh Atta Avatar answered Sep 07 '26 19:09

Suresh Atta


Why append returns a StringBuilder

So that you can append "a", "b" and "c" like this:

StringBuilder sb = new StringBuilder()
        .append("a")
        .append("b")
        .append("c");

What is returned

The StringBuilder returned is the same as the one that was called on, so this:

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = sb1.append("a")
        .append("b")
        .append("c");
System.out.println(sb1 == sb2);

Prints out true, this is why the 2 StringBuilders in your example had the same text, because they are the same StringBuilder.

like image 43
jrtapsell Avatar answered Sep 07 '26 20:09

jrtapsell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!