Both classes are mutable in nature, so you can use them when you need to do a lot of modifications to a string of characters. In this section we will see the difference between StringBuffer and StringBuilder.
Table of Contents
What are StringBuffer and StringBuilder?
StringBuffer in Java
The StringBuffer class in Java is mutable and there are many methods available in StringBuffer that directly manipulate the data inside the object. It is synchronized by default, which means when several threads act on a StringBuffer object, they are executed one by one on the object.
We can create a StringBuffer object by using new operator and by passing the string to the object. In the following example we are passing “Geeks” to the StringBuffer object.
StringBuffer sb = new StringBuffer("Geeks");
StringBuilder in Java
StringBuilder in Java is also mutable but it is not synchronized by default, so it allows multiple threads to perform tasks simultaneously. Because of this, StringBuilder may give incorrect results in some cases.
You can use any of the following statements to create StringBuilder object:
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder("Geeks"); StringBuilder sb = new StringBuilder(10);
StringBuffer Vs StringBuilder
Due to the mutability in nature, both look alike but there are also have difference between them which are as follows:
|1||StringBuffer is synchronized and hence it is thread-safe.||StringBuilder is not synchronized and it is not thread-safe.|
|2||You can use StringBuffer when multiple threads are working on the same String.||But you can StringBuilder in a single-threaded environment.|
|3||StringBuffer performance is slower when compared to StringBuilder, because it is synchronized and thread-safe.||But StringBuilder performance is faster when compared to StringBuffer.|
|4||StringBuffer is less efficient than StringBuilder.||StringBuilder is more efficient than StringBuffer.|
|5.||It ensures reliable result in multiple threads environment.||But it does not ensure reliable result in multiple threads environment.|
When should you use StringBuilder class?
Usage is based on thread, if you are not working in thread environment, you should use StringBuilder class to get faster results.