Problem with String in Java
One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. Many times we create a String and then perform a lot of operation on them e.g. converting a string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and the older one is discarded which creates lots of temporary garbage in the heap.
If String is created using String literal they remain in the String pool. To resolve this problem Java provides us, two Classes, StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.
|StringBuilder (introduced in JDK 5)
|String literals are stored in String pool whereas String Objects created using new operator are stored in Heap
|Yes – Being immutable, it is thread-safe.
|Yes – Each method in StringBuffer is synchronized
|Very Slow – as each of it’s methods are synchronized.
|When to use
|If you require immutability
|If you need mutable + thread-safety
|If you require mutable + without thread-safety