Tuesday, March 19, 2024

5 Difference between String, StringBuffer, and StringBuilder in Java

Difference between String, StringBuffer, and StringBuilder is probably one of the oldest yet most popular interview question in the history of Java developer interviews. I have personally asked this question almost 4 to 5 times. You will find this question on any list of Java interview questions. I have also included this in my earlier list of core Java questions and Java String questions. If you are preparing for Java interviews, those are handy resources. Now coming back to the answer, although all three classes StringBuffer, StringBuilder, and String are used for representing text data in Java there are some significant differences between them. One of the most notable differences between StringBuilder, StringBuffer, and String in Java is that both StringBuffer and StringBuilder are Mutable classes but String is Immutable in Java. What this means is, you can add, remove or replace characters from StringBuffer and StringBuilder object but any change on the String object like converting uppercase to lowercase or appending a new character using String concatenation will always result in a new String object. 

Another key difference between them is that both StringBuffer and String are thread-safe but StringBuilder is not thread-safe in Java. 

String achieves its thread-safety from Immutability but StringBuffer achieves it via synchronization, which is also the main difference between the StringBuffer and StringBuilder in Java.



Difference between String vs StringBuffer in Java

One of the oldest question from Java interviews are What is the difference between String and StringBuffer, it's been asked from ages, I guess started as soon as Java was released in the 90s. Let's first answer this question and then we will take a look at rather new StringBuilder vs String and StringBuffer vs StringBuilder questions.

1.Immutability

The first and foremost difference between String and StringBuffer is that the former is Immutable while the latter is mutable. This means if you need to manipulate String data then wrap it inside a StringBuffer to avoid creating lots of small and temporary String objects and putting pressure on the Garbage collector.

2. Thread Safety

Even though both StringBuffer and String are thread-safe, String achieves its thread-safety by using Immutability while StringBuffer achieves it by synchronizing methods that change the state e.g. append(), delete(), etc.

By the way, apart from the above differences, both String and StringBuffer also have some key similarities like both represent text data, both are defined in java.lang package, both classes exist in JDK from the first release and both are thread-safe in Java.

Here is also a nice diagram to highlight the mutable and immutable difference between String and StringBuffer in Java:

Difference between StringBuffer, StringBuilder and String in Java



Difference between StringBuffer vs StringBuilder in Java

One of the follow-up questions of the difference between String and StringBuffer class is the difference between StringBuilder vs StringBuffer. That's why it's not enough to know only about StringBuffer and String, you must also know about its close cousin StringBuilder which was added as a drop-in replacement of StringBuffer in the Java 1.5 release.

If you look at the code of StringBuilder.java class in JDK, you will realize that it's just StringBuffer without synchronized keywords, even comments and descriptions of methods are the same. Anyway, let's see some quick differences between StringBuffer and StringBuilder class in Java:

1. Thread Safety

The most important difference between StringBuffer and StringBuilder is that the former is thread-safe and the latter is not. Why? because all key methods of StringBuffer are synchronized, which was later removed while creating the StringBuilder class.

2. Performance

Due to the above property, their performance is also different. StringBuilder is much faster than StringBuffer. Since they are mostly used as local variables to manipulate String and not really shared between multiple threads, it's better to use StringBuilder in place of, StringBuffer.

Btw, apart from the above differences, they are also quite similar like both StringBuffer and StringBuilder represent mutable String and both allow you to append and delete characters. If you want to learn more differences between them, please join these free Java development courses, the best resources to learn Java fundamentals like this.

Difference between StringBuffer, StringBuilder and String in Java





When to use the String, StringBuffer, and StringBuilder in Java?

Now that you know the difference between these three similar classes, it's time to use that knowledge and make a decision about when to use each of them.

1) Use String if you need text data which is relatively constant e.g. names, config parameters, etc.

2) Use StringBuilder if are doing lots of String concatenation e.g. you are generating dynamic String by using programming logic.

3) Use StringBuffer when your String manipulation code is likely to be executed by multiple threads and you are sharing the instance of the same StringBuffer. It's highly unlikely and if you are doing some just stop doing it and use StringBuilder in place.

Now that you know about String and StringBuffer enough, here is a nice Java question for you to test your skills, if you know the answer, let us know in comments:

How many String objects are created in this code



That's all about the difference between String, StringBuilder, and StringBuffer in Java. Just remember that String is immutable in Java which means any modification in String will always return in new String e.g. converting into the upper or lower case or getting substring out of it. 

The key difference between String and StringBuffer is mutability. So, if you want to concatenate multiple String it's better to use StringBuffer than String.

Similarly, the key difference between StringBuilder and StringBuffer is thread-safety and speed, since StringBuffer is thread-safe it's slower than StringBuilder. This is also one of the best coding practices in Java, if you want to learn to see Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs, one of the must-reads for both intermediate and experienced Java developers.


Other Java String tutorials you may like to explore
  • How to create an array from ArrayList of String in Java? (solution)
  • How to split a String by a comma in Java? (example)
  • The difference between String literal and new() String in Java? (answer)
  • How to join String in Java using StringJoiner? (example)
  • How to use Regular Expression to Search in String? (answer)
  • How to read a text file as String in Java? (tutorial)
  • How to replace characters on String in Java? (solution)
  • How to find if String is empty in Java? (answer)
  • How to count the number of Vowels and Consonants in Java String? (solution)
  • The difference between String and StringBuffer in Java? (answer)
  • The difference between StringBuilder and StringBuffer in Java? (answer)
  • How to convert an Array to String in Java? (solution)
  • How to use the substring method in Java? (example)
  • How to use String.join() method in Java 8? (example)
  • How to convert Enumeration type to String in Java? (answer)
  • The best way to compare two Strings in Java? (answer)
  • How to reverse String in place in Java? (answer)
Thank you guys for reading this so far. Say Yes if you have been asked this question on interviews and I am sure you can now answer this with confidence. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.