Share on Facebook Share on Twitter Email
Answers.com

StringBuffer and StringBuilder

 
Wikipedia: StringBuffer and StringBuilder

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.[citation needed] 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.


Search unanswered questions...
Enter a question here...
Search: All sources Community Q&A Reference topics
 
 

 

Copyrights:

Wikipedia. This article is licensed under the Creative Commons Attribution/Share-Alike License. It uses material from the Wikipedia article "StringBuffer and StringBuilder" Read more