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());
  }

}

That 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 inefficient. So this is a great time to use a StringBuffer, because you only need one object, and more importantly, it’s much faster.