StringBuffer and StringBuilder in Java

To represent a sequence of characters, apart from string class there are 2 other classes available. But unlike String, those classes are mutable i.e; value of the string can be changed.

Those are StringBuffer and StringBuilder.

What is StringBuffer and StringBuilder?

StringBuffer is synchronized i.e. thread safe. It means two threads can’t call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

Since methods of StringBuffer are synchronized, it is slower than StringBuilder.

Let’s see an example.

public class StringTest
{
     public static void main(String[] args){
           StringBuilder builder=new StringBuilder("hello");  
           builder.append("John");

           StringBuffer buffer=new StringBuffer("Hello");  
           buffer.append("David");

           System.out.println("The builder is "+builder);
           System.out.println("The buffer is "+buffer);
   }
}