Wednesday, May 10, 2023

10 Difference between StringBuffer and StringBuilder in Java? [Answered]

Both StringBuffer and StringBuilder are two important classes in Java which represent 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 the 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 a 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 with what they do, but if that's not the case then I suggest you 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 a complete beginner then I also suggest you join a comprehensive Java course like The Complete Java Masterclass - Updated for Java 17, 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) Age
StringBuffer is present in Java and StringBuilder was added in Java 5.


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


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


4) equals and hashcode
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 like HashMap, Hashtable, and HashSet.


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


6) Thread Safety
Because of synchronization StringBuffer is considered thread-safe like 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) Performance
Another side effect of synchronization is speed. Since StringBuffer is synchronized its lot slower than StringBuilder.


8) Default Length
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) Prefer StringBuilder
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)  String concatenation
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 the 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 tutorials you may like
  • The Java Developer RoadMap (see)
  • How to sort the may by values in Java 8? (example)
  • Difference between map() and flatMap in Java 8 (answer)
  • How to use Stream class in Java 8 (tutorial)
  • 10 Courses to learn Java in-depth (courses)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to join String in Java 8 (example)
  • 15 Java Stream and Functional Programming interview questions (list)
  • How to convert List to Map in Java 8 (solution)
  • 10 examples of Optional in Java 8? (example)

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

P. S. - If you are new to the Java world and looking for a free online training course to learn Java programming then you can also check out Java Tutorials for Complete Beginners course by John Purcell on Udemy. It's completely free and you just need a Udemy account to join this course, more than 1.4 million programmers have already joined this course.

9 comments:

  1. Where are the other two points ? btw good article

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

    ReplyDelete
  3. 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

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

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

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

    ReplyDelete
  7. @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() {
    super(16);
    }

    ReplyDelete
  8. 1)In The rectangular chart,the final index should be changed to performance

    2) Can you explain the below concept with java code


    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 like HashMap, Hashtable, and HashSet.


    Deepak

    ReplyDelete
  9. Yes, thx for pointing out. Regarding your question, suppose username is string and it put on a HashMap as active login, later someone changed that string reference to other user which can create a bug. Hence, mutable objects are not good key and should not be stored in key based collections.

    ReplyDelete