When should I use StringBuffer instead of String?

By Alvin J. Alexander, devdaily.com

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, a lot of times you'll be creating a string of characters that is growing, as shown in this sample example program:

package com.devdaily.javasamples;

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 very contrived and simple, it shows the most common use of the StringBuffer class: a string of characters 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 reference named s. (Looks pretty innocent, doesn't it?) So this is a great time to use a StringBuffer, because you only need one object, and more importantly, it's much faster.


devdaily logo