Understanding String, StringBuffer and StringBuilder in Java

Introduction

In this article, we will learn about the difference between String, StringBuffer, and StringBuilder in Java. In Java, there are three classes that deal with character sequences or strings. String, StringBuffer, and StringBuilder. While all three use the purpose of representing and manipulating character sequences, they have differences in their underlying implementation and performance.

String in Java

The String class is an immutable object, which means that once a String object is created, its value cannot be changed. When you perform any operation on a String that requires modifying its value, a new String object is created with the updated value.

String str = "Hello";
str = str + " World"; // Creates a new String object 

StringBuffer in Java

The StringBuffer class is a mutable sequence of characters, which means that you can modify its value without creating a new object. It is designed to be thread-safe, which makes it suitable for use in multi-threaded environments.

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the existing StringBuffer object

In the above example, the append() method modifies the existing StringBuffer object by appending the string " World" to it.

StringBuilder in Java

The StringBuilder class is similar to StringBuffer, but it is not synchronized, which means it is not thread-safe. However, this makes it more efficient than StringBuffer in single-threaded environments.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing StringBuilder object

In the above example, Like StringBuffer, the append() method modifies the existing StringBuilder object by appending the string " World" to it.

When to use which?

  • String: Use String when you don't need to modify the character sequence after its creation. It is immutable and provides better performance in certain scenarios where the character sequence is not modified frequently.
  • StringBuffer: Use StringBuffer when you need a mutable character sequence in a multi-threaded environment. It is thread-safe but slightly less efficient than StringBuilder due to the synchronization overhead.
  • StringBuilder: Use StringBuilder when you need a mutable character sequence in a single-threaded environment. It provides better performance than StringBuffer because it doesn't have the overhead of synchronization.

Summary

If you don't need to modify the character sequence after its creation, use String. If you need a mutable character sequence in a single-threaded environment, use StringBuilder for better performance. If you need a mutable character sequence in a multi-threaded environment, use StringBuffer to ensure thread safety. By understanding the differences and use cases of these three classes, you can optimize your Java code for better performance and thread safety.