We know that Strings are immutable or constants but String builder and String buffer are basically used to provide dynamic implementation of Strings.
But String Builder is not thread safe that means more than one process can access or modify the same String builder object but String buffer is synchronized in nature.
As well as the speed of String Builder is more than String buffer.
Example :
public class Ex {
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder("name");
for (int i = 0; i < 1000; i++) {
stringBuilder.append(i+"");
}
System.out.println("time taken by string builder = " + (System.currentTimeMillis()-startTime) + " ms");
StringBuffer stringBuffer = new StringBuffer("name");
for (int i = 0; i < 1000; i++) {
stringBuffer.append(i+"");
}
System.out.println("time taken by string buffer = " + (System.currentTimeMillis()-startTime)+ " ms");
}
}
Output :
time taken by string builder = 3 ms
time taken by string buffer = 7 ms
0 Comment(s)