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

Drashti Koladiya
Quick Code
Published in
3 min readOct 20, 2021

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

Let’s first understand what String, StringBuilder, and StringBuffer are.

String

  • A String in Java is an object which represents a sequence of characters.
  • Java String is immutable which means once it is declared it cannot be changed
  • We can create String objects in 2 ways. 1) By using String literal, 2) By new Keyword.
  • String objects in Java are stored in a space called String constant pool. If the string already exists in the pool, a reference to the pooled instance is returned.

Let’s see an example below to understand the immutability and different ways to create a Java String object.

Immutability of string

StringBuilder

  • Similar to Strings, StringBuilder is also an object which represents the sequence of characters.
  • Java StringBuilder class is used to create mutable String.
  • Apart from that Java StringBuilder class is not thread-safe it means it doesn’t guarantee synchronization.

The below example shows the mutability of the StringBuilder class.

The mutability of the StringBuilder class

The below example shows why StringBuilder is not thread-safe.

Example of how StringBuilder class is not thread-safe

As we can see that we have 2 threads and each of them adds 50000 “A” characters so the ideal length of the resulting string should be 100000 but it is 98885 which is unexpected. Thus, we can clearly say that the StringBuilder class is not thread-safe.

StringBuffer

  • Similar to StringBuilder, StringBuffer is also an object which represents the sequence of characters, and it is used to create mutable String.
  • Java StringBuffer class is thread-safe. It means multiple threads can not access it at the same time and it guarantees synchronization.

The below example shows how the StringBuffer class is thread-safe and mutable.

Thread-safe and mutable StringBuffer class

Here, we can see that we have 2 threads and each of them adds 50000 “A” characters so the ideal length of the resulting string should be 100000 and it is 100000. Thus, we can clearly say that the StringBuffer class is thread-safe.

We can summarize the difference between String, StringBuilder, and StringBuffer as follows.

Difference between String, StringBuilder, and StringBuffer

--

--

Drashti Koladiya
Quick Code

Upcoming SWE intern @Instabase & SWE @Google || Former SWE intern @Google || DA-IICT’23