String vs StringBuffer vs StringBuilder

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.

   String  StringBuffer  StringBuilder (introduced in JDK 5)
 Storage Area String literals are stored in String pool whereas String Objects created using new operator are stored in Heap Heap Heap
 Immutable Yes No No
 Thread Safe Yes – Being immutable, it is thread-safe. Yes – Each method in StringBuffer is synchronized No
 Performance Fast Very Slow – as each of it’s methods are synchronized. Fast
 When to use If you require immutability If you need mutable + thread-safety If you require mutable + without thread-safety

Leave a Reply

Your email address will not be published. Required fields are marked *