String, StringBuilder and StringBuffer
As we all know that String is immutable. That means it’s safe to use String among multiple threads. And every change to String will create a new String instance. Then why do we still have another 2 string classes StringBuilder and StringBuffer?
StringBuilder is a mutable version of String. When we do change on the StringBuilder, actually we change the underlying char array. So if a string needs to be modified for multiple times, it’s recommended to use StringBuilder.
StringBuffer is a thread safe mutable version of String. Each of its method is marked with synchronized. Many people don’t use StringBuilder and StringBuffer correctly. If no multiple threads access requirement, StringBuilder should be used. Cause it’s faster then the synchronized version.
BTW, there’s a pattern called immutable pattern. We create a class whose state cannot be changed externally. So it’s safe to be used in concurrent programming. At the same time, we also provide a mutable version of the class. Their constructor can accept each other’s instance. It’s a common pattern in java libraries.