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.
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);}}
StringBuffer
object buf
.from Educative !!!
to String Buffer object buf
.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);}}
StringBuilder
object builder
.from Educative !!!
to the String Builder object builder
.