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?
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");
StringBuilderSo that you can append "a", "b" and "c" like this:
StringBuilder sb = new StringBuilder()
.append("a")
.append("b")
.append("c");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With