Wednesday, May 15, 2019

10 Differences between StringBuffer and StringBuilder in Java

Both StringBuffer and StringBuilder are two important classes in Java which represents mutable String i.e. the String object, whose value can be changed. Since String is Immutable in Java, any change or operation on String object e.g. converting it to upper or lower case, adding character, removing a character, or getting a substring, all results in a new String object. This can put a lot of pressure on Garbage collector if your application generates lots of throws away String instances. To avoid this issue, Java designer presented initially StringBuffer class and later StringBuilder as mutable String. That's the main difference between String vs StringBuffer and StringBuilder and also one of the frequently asked Java questions for beginners.

Anyway, when StringBuffer was introduced it has its own problem e.g. it was synchronized, methods like append have synchronized and hence they were slower. Even if you use them by just one thread and don't share with other threads, the cost of acquiring and releasing lock due to Synchronization is still significant.

Since StringBuffer is mostly used as local mutable String variable making it synchronized wasn't a great decision and Java designer realized their mistake and corrected it in Java 1.5 by introducing the StringBuilder class.

Btw, StringBuilder is nothing but a drop in like to like a class for StringBuffer except that its method was not synchronized.  In this article, I'll tell you some of the important points you should know about StringBuilder and StringBuffer class.

I assume that you have used these classes in your Java program and familiar of what they do, but if that's not the case then I suggest you to first get familiar with them by writing some programs. One interesting one is reversing String as StringBuffer got the reverse() method which is not available to String class.

If you are complete beginner then I also suggest you join a comprehensive Java course like The Complete Java Masterclass - Updated for Java 11, which is both comprehensive and updated. It's also not very expensive as you can buy it within a cost of sandwich on Udemy's flash sale.

10 Differences between StringBuffer and StringBuilder in Java

As I have said that both StringBuffer and StringBuilder are a mutable alternative of String class and you can change the content without creating additional objects. Here are some more key differences between StringBuilder and StringBuffer in Java:

1) StringBuffer is present in Java and StringBuilder was added in Java 5.

2) Both StringBuffer and StringBuilder represents mutable String which means you can add/remove characters, substring without creating new objects.

3) You can convert a StringBuffer into String by calling toString() method.

4) Both StringBuilder and StringBuffer doesn't override equals() and hashCode() method because they are mutable and not intended to be used as a key in hash-based collection classes e.g. HashMap, Hashtable, and HashSet.

5) StringBuffer is synchronized which means all method which modifies the internal data of StringBuffer is synchronized e.g. append(), insert() and delete(). On contrary, StringBuilder is not synchronized.

6) Because of synchronization StringBuffer is considered thread safe e.g. multiple threads can call its method without compromising internal data structure but StringBuilder is not synchronized hence not thread safe. See The Complete Java Masterclass for more details.

Differences between StringBuffer and StringBuilder in Java

7) Another side effect of synchronization is speed. Since StringBuffer is synchronized its lot slower than StringBuilder.

8) The default length of StringBuffer is 16 characters. You should explicitly define the size of it, especially if you know that size would be less or more than 16 to avoid wasting memory and spending time during resize.

9) In general, you should always use StringBuilder for String concatenation and creating dynamic String unless and until you are absolutely sure that you need StringBuffer.

10) The string concatenation done using + (plus) operator internally uses StringBuffer or StringBuilder depending upon which Java version you are using. For example, if you are running in Java 5 or higher than StringBuilder will be used and for the lower version, StringBuffer will be used.

Further Learning
The Complete Java Masterclass - Updated for Java 11
Java Fundamentals: The Java Language
Data Structures and Algorithms: Deep Dive Using Java
Java, A Beginners Guide - 7th Edition

That's all about some important differences between StringBuffer and StringBuilder in Java. As I have said before and in this article, both can be used to create dynamic String but one is thread-safe and other is not. In general, you should use StringBuilder because it's fast as it doesn't have to worry about thread-safety and synchronization.

But, if you know that multiple threads can append or change the content of StringBuilder at the same time then you can switch to StringBuffer, which is slightly slower but thread-safe.

Other Java String articles you may like to explore:

Thanks for reading this article so far, if you like this article then please share with your friends and colleagues. If you have any question then please drop a comment.


shivasurya said...

Where are the other two points ? btw good article

javin paul said...

Hello Shivasurya, for now, yup, just 8 points, will add 2 more points when I know, if you know, please share.

Unknown said...

Since StringBuffer is synchronized its lot slower than StringBuilde

Is it really? The JVM performs a neat trick called lock elision to avoid the cost of locking on objects that are only visible to one thread.

I depends

Anonymous said...

what is the meaning of overriding equals()? can you explain it in easier way please

Anurag said...

Good article! It helped me a lot in my interview. This question will be asked for sure in java interviews. A must read.

Megha said...

Default size of StringBuffer is 2^31-1 and not 16

Unknown said...

@Megha, this is what I see in JDK source,

* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
public StringBuffer() {

Post a Comment

Pepperjam Verification