What is the difference between stringbuilder and stringbuffer?
StringBuilder is mutable & synchronized
StringBuffer is mutable & not synchronized.
StringBuilder is immutable & not synchronized
StringBuffer is mutable & synchorinzed
First lets see the similarities:
Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.
StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.
Meaning of synchronized (synchronization):
When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect.
StringBuffer is synchronized, so you can use it with multiple threads with out any problem.
Which one to use when?
StringBuider : When you need a string, which can be modifiable, and only one thread is accessing and modifying it.
StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.
Note : Don't use StringBuffer unnecessarily. Means, don't use it if only one thread is modifying and accessing it. Because it has lot of locking and unlocking code for synchronization which will un necessarily take up CPU time. Don't use locks unless it is required.
String is an immutable class while StringBuilder & StringBuffer are mutable classes. StringBuffer is synchronized while StringBuilder is not.
Below link can be useful to find more differences between String, StringBuffer & StringBuilder
<a href="http://newtechnobuzzz.blogspot.com/2014/07/difference-between-string-stringbuffer.html">Difference between String, StringBuffer and StringBuilder</a>
Back To Top