StringBuffer and StringBuilder

From Free net encyclopedia

Revision as of 22:27, 26 February 2006; view current revision
←Older revision | Newer revision→

The Template:Javadoc:SE class is one of two core string classes in the Java programming language. Most of the time, the Template:Javadoc:SE class is used, however, the StringBuffer class is a mutable object while String is immutable. That means the contents of StringBuffer objects can be modifed 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 Template:Javadoc:SE 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 Template:Javadoc:SE package.

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

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

Moreover, the Java compiler (e.g., javac) usually uses 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 = ");
sbuf.append(a);
sbuf.append(b);
String s = sbuf.toString();

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