What is the difference between String, StringBuilder and StringBuffer in Java, and when do you use each one?
There are three classes, and they each do a different job.
A String cannot be changed. Every operation that looks like it changes the text gives you a new string instead. It is the right choice when the text is a fixed value that you will read and pass around, such as a name, a label or a key in a map.
A StringBuilder can be changed. It keeps a piece of memory that it grows as you add to it, and it does not make a copy of the text every time you add something. It is not safe to use from more than one thread at the same time. It is the right choice when you are building one piece of text in one thread, which is the common case.
A StringBuffer can also be changed, and every one of its methods is safe to use from several threads at once. It does the same job as a StringBuilder, but it takes a lock every time you use it, so it is slower. It is the right choice only when several threads really do have to build the same piece of text.
public class Main {
public static void main(String[] args) {
String a = "abc";
StringBuilder b = new StringBuilder("abc");
StringBuffer c = new StringBuffer("abc");
// A String gives you a new one.
String changed = a.concat("def");
System.out.println("String : " + a + " / " + changed);
// The other two change in place.
b.append("def");
c.append("def");
System.out.println("StringBuilder: " + b);
System.out.println("StringBuffer : " + c);
// A StringBuilder is not safe to share between threads.
// A StringBuffer is.
System.out.println("StringBuilder is safe : " + isThreadSafe(b));
}
static boolean isThreadSafe(Object builder) {
return builder instanceof StringBuffer;
}
}
The next question in this topic looks at why the choice matters so much for speed.