JAVA: How do StringBuffers work?

new StringBuffer(), creates a StringBuffer with capacity of 16 characters.



Java String concatentation operator (+) is implemented using the StringBuffer class

Given:
  String a = "a";
  String b = "b";
  String c = "c";

The following produces the same results at run-time (speed, memory allocation).
  a + b + c
  new StringBuffer().append(a).append(b).append(c).toString();



When does it make sense to use StringBuffer?
  String d = a + b;
  d = d + c;

This now gets compiled into:
  String d = new StringBuffer().append(a).append(b);
  d = new StringBuffer().append(d).append(c);

This obviously is more costly/slower than:
  String d = new StringBuffer().append(a).append(b);
  d.append(c);

No comments: