4

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?

Arvind Katte
  • 995
  • 2
  • 10
  • 20
dBio
  • 87
  • 2
  • 6
  • https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#append(java.lang.String) returns a reference thats why. – LazerBanana Nov 23 '17 at 14:09

2 Answers2

3

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();
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 3
    equivalent, but they will differ in speed and how JVM recognizes this code. https://stackoverflow.com/questions/44334233/why-is-the-stringbuilder-chaining-pattern-sb-appendx-appendy-faster-than-reg – Eugene Nov 23 '17 at 14:12
2

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();
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43