StringBuffer and StringBuilder

From Wikipedia, the free encyclopedia

The StringBuffer class is one of three core string classes in the Java programming language. Most of the time, the String class is used, however, the StringBuffer class is a mutable object while String is immutable. That means the contents of StringBuffer objects can be modified while similar methods in the String class that appear to modify the contents of the string actually return a new String object. It is more efficient to use a StringBuffer instead of operations that result in the creation of many intermediate String objects. The StringBuilder class, introduced in J2SE 5.0, differs from StringBuffer in that it is unsynchronized. When only a single thread at a time will access the object, using a StringBuilder is more efficient than using a StringBuffer.

StringBuffer and StringBuilder are included in the java.lang package.

The following example code uses StringBuffer instead of String for performance improvement.

StringBuffer sbuf = new StringBuffer(300);
for (int i = 0; i < 100; i++) {
  sbuf.append(i);
  sbuf.append('\n');
}

Moreover, the Java compiler (e.g., javac) usually uses StringBuilder (or StringBuffer) to concatenate strings and objects joined by the additive operator. For example, one can expect that

String s = "a + b = " + a + b;

is translated to

StringBuffer sbuf = new StringBuffer(32);
sbuf.append("a + b = ").append(a).append(b);
String s = sbuf.toString();

In the above code, a and b can be almost anything from primitive values to objects.

Languages