Java StringBuilder append methods chain

Viewed 2676

I have a question. For instance:

StringBuilder sb = new StringBuilder();
sb.append("Teacher,");
String s = sb.append(" Good").append("Morning!").toString();

Now in the last line I made a chain of two append methods. I know that each method append method returns an address to the string in memory (I am correct? right?). So in the first sb.append it's appending to the address that sb points to. And the first sb.append is getting executed first in Run-Time but then what happens with the next .append? the next .append is working with the address that the first append method returned or I am wrong? This is what I mean:

First append -> sb.append(" Good"); Second append returnedAddr.append("Morning!");

Is it working in this way?

2 Answers

sb.append(" Good") returns a reference to the same StringBuilder instance on which the method was called, which allows you to chain another .append() call to it.

StringBuilder sb = new StringBuilder();
sb.append("Teacher,");
String s = sb.append(" Good").append("Morning!").toString();

is equivalent to

StringBuilder sb = new StringBuilder();
sb.append("Teacher,");
sb.append(" Good");
sb.append("Morning!");
String s = sb.toString();

append() on StringBuilder just returns this as a convenience.

String s = new StringBuilder().append("Good").append(" Morning!").toString();

is equivalent to

StringBuilder sb = new StringBuilder();
sb.append("Good");
sb.append(" Morning!");
String s = sb.toString();
Related