What are the differences of String, StringBuffer, and StringBuilder in Java? When we talk about Strings, we’re typically referring to instances of joined characters. Strings can be created with the declaration of String or generating an instance of a StringBuffer or StringBuilder in Java.

String

String example = "example";

If we want to change example, we lose the reference to the original object. Each modification of a String creates a new instance of the String in Java.

example += " added";

A new copy of the String is created to add the extra content to example. As you modify the String, you add space and time complexity of n (length of String size) because you are creating new instances of the String in Java.

String[] words;
String sentence = "";
for (String w : words){
    sentence += w;
}

When looping through an array of Strings and concatenating the contents of the array to a String, Java copies the two Strings in every loop to create each instance of sentence at the time of the loop. Every character within each String is copied one by one fully.

Let’s say m is the size of the words array. If n is the size of sentence, then we’re copying n characters for the first iteration of the loop. For the second loop, we copy 2n characters. For the third loop, we copy 3n characters and so on. The total time complexity is O(n + 2n + ... + nm), which reduces to O(nm²). When performing simple concatenations, we find out that String isn’t very fast.

 

StringBuffer and StringBuilder

Usually, initiating and declaring Strings is not an issue unless we do lots of modifications. But if we do, then StringBuffer and StringBuilder can help us avoid the potential problem. StringBuffer and StringBuilder create an array of the Strings, copying them back to the string only when necessary. As a result, for simple concatenations or modifications, both are faster than String.

 

StringBuffer vs StringBuilder

StringBuffer and StringBuilder both store the String in the heap. The difference is that StringBuffer is synchronized, meaning thread safe. This means that two threads can’t call StringBuffer methods simultaneously. On the other hand, StringBuilder is non-synchronized, meaning not thread safe. This means that multiple threads can call StringBuilder methods simultaneously.

StringBuilder is faster than StringBuffer, but you may encounter thread conflicts if you’re using multiple simultaneous calls.

StringBuffer example = new StringBuffer("example");
example.append(" added");
StringBuilder example = new StringBuilder("example");
example.append(" added");

 

Performance Differences

String time: 500ms
StringBuffer time: 3ms
StringBuilder time: 1ms

The running times may be slightly different for you depending on your computer. The observation that we make is the same. For simple concatenations, StringBuilder > StringBuffer > String in time complexity.