What are the differences between StringBuilder and StringBuffer?

Overview

A string is a representation of characters. Java comes with three types of classes to represent and manipulate strings: String, StringBuilder, andStringBuffer. The String class is an immutable class, and the other two classes are mutable. The StringBuilder and StringBuffer classes look similar but they have some differences. Let's look at them in the table below.

String Buffer

String Builder

It was introduced in the initial version of Java, Java 1.0.

It was introduced in Java 1.5.

It is synchronized.

It is non-synchronized.

It is thread safe, meaning that two threads can't call string buffer at the same time.

It is not thread safe, meaning that two threads can call the string buffer at the same time.

It is less efficient than String Builder.

It is more effiecient than String Buffer.

Let's look at the implementation of both classes.

Example of StringBuffer

class HelloWorld {
public static void main( String args[] ) {
//construct buffer object
StringBuffer buf =new StringBuffer("Hello");
//append the string to buffer
buf.append(" from Educative !!!");
System.out.println(buf);
}
}

Explanation

  • Line 4: We construct a new StringBuffer object buf.
  • Line 7: We append the string from Educative !!! to String Buffer object buf.

Example of StringBuilder

class HelloWorld {
public static void main( String args[] ) {
//construct string builder object
StringBuilder builder =new StringBuilder("Hello");
//append the string to builder
builder.append(" from Educative !!!");
System.out.println(builder);
}
}

Explanation

  • Line 4: We construct a new StringBuilder object builder.
  • Line 7: We append the string from Educative !!! to the String Builder object builder.

Free Resources