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 objectStringBuffer buf =new StringBuffer("Hello");//append the string to bufferbuf.append(" from Educative !!!");System.out.println(buf);}}
Explanation
- Line 4: We construct a new
StringBufferobjectbuf. - Line 7: We append the string
from Educative !!!to String Buffer objectbuf.
Example of StringBuilder
class HelloWorld {public static void main( String args[] ) {//construct string builder objectStringBuilder builder =new StringBuilder("Hello");//append the string to builderbuilder.append(" from Educative !!!");System.out.println(builder);}}
Explanation
- Line 4: We construct a new
StringBuilderobjectbuilder. - Line 7: We append the string
from Educative !!!to the String Builder objectbuilder.