StringBuffer vs StringBuilder in Java
Last Updated :
15 Oct, 2024
Java provides three classes to represent the sequence of characters i.e. String, StringBuffer, and StringBuilder. A string is immutable in Java whereas, both StringBuffer and StringBuilder are mutable. This means they allow modifications to the character sequence without creating new objects.
The main difference between StringBuffer
and StringBuilder
is that StringBuffer
is thread-safe due to synchronization and this is slower. On the other hand, StringBuilder is faster but not thread-safe and is introduced in JDK 1.5. If we do not need thread safety, StringBuilder
is the better choice due to its speed. We typically do not need thread safety when solving interview questions, competitive coding questions, and single-threaded applications. Use StringBuffer
only when dealing with multiple threads modifying the same string.
Now let’s deep dive into StringBuffer vs StringBuilder in Java.
StringBuilder vs StringBuffer in Java
Below is the key differences table of StringBuffer and StringBuilder.
StringBuffer | StringBuilder |
---|
StringBuffer is present since early versions of Java. | StringBuilder was introduced in Java 5 (JDK 1.5). |
StringBuffer is synchronized. This means that multiple threads cannot call the methods of StringBuffer simultaneously. | StringBuilder is asynchronized. This means that multiple threads can call the methods of StringBuilder simultaneously. |
Due to synchronization, StringBuffer is called a thread safe class. | Due to its asynchronous nature, StringBuilder is not a thread safe class. |
Due to synchronization, StringBuffer is lot slower than StringBuilder. | Since there is no preliminary check for multiple threads, StringBuilder is a lot faster than StringBuffer. |
Use in multi-threaded environments.
| Use in single-threaded or non-concurrent environments.
|
StringBuffer Class
StringBuffer
is a class that allows us to create and modify a flexible, expandable sequence of characters. It is thread-safe. Thismeans that it can be safely used when multiple threads are accessing or modifying the string concurrently. But due to synchronization, it is slower than StringBuilder
.
StringBuffer str = new StringBuffer();
Example:
Below is an example which implements the StringBuffer class.
Java
// Java program to demonstrate
// the StringBuffer class
public class GFG {
// Driver code
public static void main(String args[])
{
// Creating a new StringBuffer
StringBuffer str
= new StringBuffer("Hello");
str.append(" World!");
System.out.println(str);
}
}
StringBuilder Class
StringBuilder
is similar to StringBuffer
, but it is not synchronized. Thismeans it is not thread-safe. But it is much faster than StringBuffer
and is suitable for use in scenarios where thread safety is not required (e.g., competitive coding, interview questions).
StringBuilder str = new StringBuilder();
Example:
Below is an example which implements the StringBuilder class.
Java
// Java program to demonstrate
// the StringBuilder class
public class GFG {
// Driver code
public static void main(String args[])
{
// Creating a new StringBuilder
StringBuilder str
= new StringBuilder("Hello");
str.append(" World!");
System.out.println(str);
}
}
Conversion from StringBuffer to StringBuilder
The StringBuffer cannot be directly converted to StringBuilder. We first need to convert the StringBuffer to a String object by using the inbuilt method toString() method. After converting it to a string object, we can simply create a StringBuilder using the constructor of the class.
For example:
Java
// Java program to demonstrate
// the conversion between the
// StringBuffer and StringBuilder
// class
public class GFG {
// Driver code
public static void main(String args[])
{
StringBuffer sbr
= new StringBuffer("Geeks");
// Conversion from StringBuffer
// object to the String object
String str = sbr.toString();
// Creating a new StringBuilder
// using the constructor
StringBuilder sbl
= new StringBuilder(str);
System.out.println(sbl);
}
}
Conversion from StringBuilder to StringBuffer
Similar to the above conversion, the StringBuilder cannot be converted to the StringBuffer directly. We first need to convert the StringBuilder to the String object by using the inbuilt method toString().
Now, we can create a StringBuilder using the constructor.
For example:
Java
// Java program to demonstrate
// the conversion between the
// StringBuilder and StringBuffer
// class
public class GFG {
// Driver code
public static void main(String args[])
{
StringBuilder sbr
= new StringBuilder("Geeks");
// Conversion from StringBuilder
// object to the String object
String str = sbr.toString();
// Creating a new StringBuffer
// using the constructor
StringBuffer sbl
= new StringBuffer(str);
System.out.println(sbl);
}
}
Conclusion
When deciding between StringBuffer
and StringBuilder
, the key factor is thread safety. If thread safety is not required, prefer StringBuilder
for its speed and performance. For multi-threaded applications where the same String is modified by multiple threads, StringBuffer
is a safer option but it is slower due to synchronization.
Similar Reads
String vs StringBuilder vs StringBuffer in Java
A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. In Java, String, StringBuilder, and StringBuffer are used for handling strings. The main difference is: String: Immutable, meaning its value cannot be changed onc
6 min read
Difference Between StringBuffer and StringBuilder in Java
Java provides three classes to represent the sequence of characters i.e. String, StringBuffer, and StringBuilder. A string is immutable in Java whereas, both StringBuffer and StringBuilder are mutable. This means they allow modifications to the character sequence without creating new objects. The ma
4 min read
When to use Rope over StringBuilder in Java?
What are Ropes? Rope is a binary tree data structure where each node except the leaf contains the number of characters present to the left of the node. They are mainly used by text editors to store and manipulate large strings. It provides different string operations such as append, insert and delet
3 min read
Storage of String in Java
In Java, we know both Stack and Heap space are part of Java Virtual Machine (JVM). However, these memory spaces are used for different purposes. Stack space contains specific values that are short-lived whereas Heap space is by Java Runtime to allocate memory to objects and JRE classes. In Java, str
3 min read
StringBuffer toString() method in Java with Examples
The toString() method of StringBuffer class is the inbuilt method used to returns a string representing the data contained by StringBuffer Object. A new String object is created and initialized to get the character sequence from this StringBuffer object and then String is returned by toString(). Sub
2 min read
StringBuffer substring() method in Java with Examples
In StringBuffer class, there are two types of substring method depending upon the parameters passed to it. substring(int start) The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The strin
3 min read
StringBuffer Class in Java
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters. Features of StringBuffer ClassThe key features of StringBuffer
11 min read
String Literal Vs String Object in Java
Compare string initialization performance for String Literal and String object. String Literal String str = "GeeksForGeeks"; This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there
2 min read
StringBuffer subSequence() in Java with Examples
The subSequence(int start, int end) method of StringBuffer class is the inbuilt method used to return a subsequence of characters lie between index start and end-1 of this sequence. The subsequence starts with the char value at the index start and ends with the char value at (end-1). The length of t
3 min read
StringJoiner toString() method in Java
The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are
2 min read