Difference between String , StringBuilder and StringBuffer

Last modified date

Comments: 0

String, StringBuidler and StringBuffer are all different methods of creating and using Strings in Java. This article explains the difference between them and when you should use them in Java.

String

String in Java represents character Strings. They are immutable meaning that is thread safe, however every time there are any manipulations performed on the String, a new String object is created and the old one is discarded ready for garbage collection.

Therefore manipulation on Strings are costly operations, so if you are going to be performing lots of manipulations on Strings, it is advisable to use a mutable String object such as StringBuffer.

StringBuffer

StringBuffer is a mutable object class in Java and it also synchronized and therefore thread safe.

However, this sychronization and thread safety come at a performance cost, so if you are using a single threaded application or you are not concerned with thread safety then you should use StringBuilder. If you require thread safety then use StringBuffer.

StringBuilder

StringBuilder is a mutable object class in Java that provides no guarantee of synchronization.

It is more performant than a StringBuffer as a result but should only be used in single thread applications or where thread safety is not a concern.

If you found this useful, you may also be interested in reading our OOP Principles Guide.

JakTech

Leave a Reply

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

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.