Interview question: What’s the difference between String, StringBuffer, and StringBuilder in Java?
1. StringBuffer and StringBuilder are mutable. String is not.
2. String and StringBuffer are thread safe. StringBuilder is not.
In Java, the String class is immutable, meaning once it is constructed it cannot be changed without constructing a new instance of the object. One inherent advantage to immutable objects in Java is they are thread safe. Constructed instances of the String class in Java are stored in a special area of memory called the String pool.
Unlike the String class, both StringBuffer and StringBuilder are mutable, meaning its value can change after construction. Both instances of StringBuffer and StringBuilder are allocated on the Java runtime heap. It is possible to append to or clear the String data stored within a instance of a StringBuffer or a StringBuilder.
The different between the StringBuffer and StringBuilder class is that StringBuffer is thread safe while StringBuilder is not. StringBuffer accomplishes thread safety, not by being immutable like an instance of the String class, but rather by synchronizing all methods in the class. The synchronized keyword in a method declaration in Java ensures that only one thread is within a method at a time. While this sounds very appealing, one may wonder why StringBuffer isn’t always used instead of StringBuilder? The answer is simple; performance. Synchronizing methods in Java comes with an overhead.
The next logical question is when should you use String, StringBuffer, or StringBuilder? For dealing with simple String literals without concatenation and outside of loops, it is best to use the String class. Inside of loops such as while loops or for loops where a String is being appended to, it is best to use StringBuffer or StringBuilder. When thread safety is not a concern, such a local variable within a method, it is always preferable to use StringBuilder over StringBuffer.