Java StringBuffer versus String: When to use StringBuffer

Java StringBuffer FAQ: When should I use a StringBuffer instead of a String?

The most common reason to use a StringBuffer instead of a String in your Java programs is when you need to make a lot of changes to a string of characters. For instance, many times you’ll be creating a string of characters that is growing, as shown in this example:

public class JavaStringBufferExample {

  public static void main(String[] args) {
      StringBuffer sb = new StringBuffer();
      for (int i=0; i<1000; i++) {
          sb.append(i);
      }
      System.out.println(sb.toString());
  }

}

While that program is contrived and simple, it shows the most common use of the StringBuffer class: you’re creating a string of characters that is going to be growing. In this case you don't want to do something like this:

String s = "";
for (int i=0; i<1000; i++) {
    s = s + i;
}

You don’t want to do this because String objects are immutable — they can’t be modified — so what this segment of code really does is to create at least 1,000 String objects and then assign them to the variable named s. So while this code looks pretty innocent, it’s actually incredibly inefficient. So this is a great time to use a StringBuffer, because you only need one object, and more importantly, it’s much faster.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.