What is the difference between String, StringBuffer, and StringBuilder?

By | December 19, 2019

String is an elementary and essential class in the Java language, which provides various basic logic for constructing and managing strings. It is a typical Immutable class, declared as a fnal class, and all attributes are also fnal. Because of its immutability, actions such as stitching and cutting strings will generate new String objects. Due to the universality of string operations, the efficiency of related operations often has a significant impact on application performance.

StringBuffer is a class provided to solve the problem mentioned above of splicing too many intermediate objects. We can use the append or add a method to add the string to the end of the existing sequence or specify the position. StringBuffer is essentially a thread-safe and modifiable character sequence, which guarantees thread safety and also brings additional performance overhead, so unless there is a need for thread safety, it is recommended to use its successor, which is StringBuilder.

StringBuilder is new in Java 1.5, and it has no essential difference from StringBuffer in terms of capabilities, but it removes the thread-safe part, effectively reduces overhead, and is the first choice for string stitching in most cases.