Home »
Java programming language
Comparision of StringBuffer and StringBuilder in Java
In this article, we are going to learn the difference between StringBuffer and StringBuilder in java.
Submitted by Jyoti Singh, on February 21, 2018
StringBuffer and StringBuilder are two classes of java, which are used for string. These are used whenever there is a need of a lot of modification to Strings. StringBuffer and StringBuilder objects can be modified again and again.
The only difference between StringBuffer and String Builder is that, StringBuilder methods are not synchronized that is they is not thread safe as two threads can call the StringBuilder methods simultaneously. On the other hand String Buffer is thread safe.
It’s better to use StringBuilder as it’s much faster than String Buffer.
Let’s take an example to check which one is faster.
public class ExComparison2 {
public static void main(String arg[])
{
long st,et;
StringBuffer str1=new StringBuffer();// String buffer class object
st=System.currentTimeMillis(); // recording current time
for(int i=0;i<1000000;i++)
{
//append method of string buffer add the data in string object.
str1.append("Testing StringBuffer ");
}
et=System.currentTimeMillis();
System.out.println("String Buffer Takes "+(et-st)+" milliSeconds");
//(et-st) shows the time taken by the String buffer.
StringBuilder str2=new StringBuilder();//String Builder class object
st=System.currentTimeMillis();
for(int i=0;i<1000000;i++)
{
//append method of string buffer add the data in string object.
str2.append("Testing StringBuffer ");
}
et=System.currentTimeMillis();
System.out.println("String Builder Takes "+(et-st)+" milliSeconds");
////(et-st) shows the time taken by the String builder.
}
}
Output
As you can see StringBuilder takes less time than StringBuffer.
TOP Interview Coding Problems/Challenges