Strings in Java are immutable, meaning you cannot change the value of a String object. However, if we try to modify the value of a String object in Java, a new String object with the updated value will be created in the heap memory. Therefore, to handle this problem, there exist two classes in Java called StringBuffer and StringBuilder, which are mutable, meaning that you can change the value of the String object using them.
Difference Between StringBuffer and StringBuilder in Java
Some of the key differences between the StringBuffer and StringBuilder in Java are given below:
Parameters
StringBuffer
StringBuilder
Synchronisation
StringBuffer is synchronised.
StringBuilder is not synchronised.
Performance
Due to the synchronisation, the performance gets low.
As there is no synchronisation, the performance is high.
Thread Safety
There is thread safety.
There is no thread safety.
Methods
It has various methods, including append(), insert(), etc.
It has the same method as the StringBuffer but some may not be there.
Use Case
It is used where thread safety is a priority and needs synchronisation.
It is used where thread safety is a priority not needed.
Memory Overhead
It is higher due to synchronisation.
It is lower due to a lack of sync.
Introduction in Java
Introduced in JDK 1.0
Introduced in JDK 1.5
Constructor
There are many constructors, such as StringBuffer(), StringBuffer(int capacity), StringBuffer(String str), etc.
There are many constructors, such as StringBuilder(), StringBuilder(int capacity), StringBuilder(String str), etc.
Capacity
There is a default capacity of 16, but can be expanded using the doubling method.
There is also a default capacity of 16, but it can be expanded using the doubling method.
Memory Efficiency
It is similar in both.
It is similar in both.
Thread System
It is recommended for multi-threaded systems.
It is recommended for single-threaded systems.
Syntax
StringBuffer strBuffer = new StringBuffer(“Hello World”);
StringBuilder strBuilder = new StringBuilder(“Hello World”);
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
What are Strings in Java?
Strings in Java are the sequence of immutable characters (that you cannot change the value of a String object) in nature. Any operation that appears to modify a String creates a new String object in the heap. But because the String in Java are immutable, they can be shared. The string uses UTF-16 encoding for the character stream in Java.
Syntax of String in Java:
String str = “hello world”;
Explanation:
The above is a String created with a variable named “str” that contains an immutable value “hello world”.
What is StringBuffer in Java?
StringBuffer is a type of String which is mutable. A StringBuffer’s object value can be changed as it represents the mutable sequence of characters. A StringBuffer is called thread safe because it is used for multiple threads systems. StringBuffer supports sync which demonstrates that no more than one thread may simultaneously call a StringBuffer method. The trade-off for thread safety is performance. StringBuffer operations tend to be slower due to the overhead of synchronisation. Every StringBuffer has the capacity to hold a large length of sequence of characters and doesn’t require the allocate a new internal buffer array. If needed, it will automatically make it larger.
The main functions of the StringBuffer are the append and insert methods, which are overloaded to accept data of any type. These methods convert the given data to a string and then append or insert the characters of that string into the string buffer. But there is a difference in both where the append method always adds the string characters at the end of the buffer whereas the insert method adds the characters at a specified point.
Syntax of StringBuffer in Java:
// Creating a new StringBuffer instance
StringBuffer strBuf = new StringBuffer("Hello World");
Explanation:
The above is a syntax of StringBuffer instance created with a variable named “strBuf” that contains a mutable value “Hello World” of an object.
StringBuffer Constructors
StringBuffer()- This constructor constructs a string buffer with empty characters and with an initial capacity of 16 characters at max.
StringBuffer(CharSequence seq)- This constructor constructs a string buffer that contains the same characters as the CharSequence.
StringBuffer(int capacity)- This constructor constructs a string buffer with empty characters and the specified initial capacity.
StringBuffer(String str)- This constructor constructs a string buffer initialised to the contents of the string in the parameters.
StringBuffer Methods
append()- It appends the specified string to the current sequence.
insert()- It inserts the specified string to the specified position in the sequence.
replace()- It replaces the characters in a substring of this sequence with characters in the specified string.
delete()- It removes the characters in a substring of this sequence.
deleteCharAt()- It removes the character at the specified position.
reverse()- It reverses the character’s sequences.
toString()- It returns the string representing the given data.
length()- It returns the string length.
capacity()- It gives the current capacity of a given sequence.
charAt()- It returns the character to a specified position in the sequence.
setCharAt()- It sets a specified character at a specified position in the sequence.
substring()- It returns a new String that contains a subsequence of characters currently contained in this sequence starting from the specified index.
indexOf()- It returns the index within this string of the first occurrence of the specified substring.
lastIndexOf()- It returns the index within this string of the last occurrence of the specified substring
setLength()- It sets the length of the character sequence.
Code Example: The below example demonstrates the usage of the append() method of StringBuffer in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuffer object with an initial string value
StringBuffer mySb = new StringBuffer("Hello,");
// Appending different types of data to the StringBuffer class object
mySb.append(" World");
mySb.append('!');
mySb.append(2025);
mySb.append(false);
// Printing the result from the StringBuffer
System.out.println(mySb);
}
}
Explanation:
In this example, we are using the append() method to append the different types of data into a StringBuffer and finally printing the results from the StringBuffer.
Output:
Hello, World!2025false
Code Example: The below example demonstrates the usage of the insert() method of StringBuffer in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuffer object with an initial string value
StringBuffer mySb = new StringBuffer("Hero Vide!!");
// inserting different types of data to the StringBuffer class object at a specific index
mySb.insert(10, " Java");
mySb.insert(0, "Welcome, ");
mySb.insert(24, 2024);
// Printing the result from the StringBuffer
System.out.println(mySb);
}
}
Explanation:
In this example, we are using the insert() method to insert the different types of data at a specified position into a StringBuffer and finally printing the results from the StringBuffer.
Output:
Welcome, Hero Vide! Java2024!
Code Example: The below example demonstrates the usage of the length() method of StringBuffer in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuffer object with an initial string value
StringBuffer mySb = new StringBuffer("Hero Vide!!");
// Printing the before change length of the StringBuffer
System.out.println("Length before change: " + mySb.length());
// Appending some more text to update the string
mySb.append(" Welcome to the world of Java!");
// Printing the updated length
System.out.println("Updated Length after change: " + mySb.length());
}
}
Explanation:
In this example, we are using the length() method to get the length of a string and printing it. We are also updating the string length and again printing the length of the modified string from the StringBuffer.
Output:
Length before change: 11
Updated Length after change: 41
What is StringBuilder in Java?
StringBuilder is a type of String which is mutable. A StringBuilder’s object value can be changed as it represents the mutable sequence of characters. A StringBuilder is also a thread-safe class because it is used for multiple threads systems. StringBuilder is the same as StringBuffer, but it doesn’t support synchronisation.
Like StringBuffer, every StringBuilder also has the capacity to hold a large length of sequence of characters and doesn’t require the allocate a new internal buffer array. If needed, it will automatically make it larger.
The main functions of the StringBuilder are the same as of a StringBuffer i.e., append and insert methods, which are overloaded to accept data of any type. These methods convert the given data to a string and then append or insert the characters of that string into the string builder. But there is a difference in both where the append method always adds the string characters at the end of the builder whereas the insert method adds the characters at a specified point.
StringBuilder Constructors
StringBuilder()- This constructor constructs a string builder with empty characters and with an initial capacity of 16 characters at max.
StringBuilder(CharSequence seq)- This constructor constructs a string builder that contains the same characters as the CharSequence.
StringBuilder(int capacity)- This constructor constructs a string builder with empty characters and the specified initial capacity.
StringBuilder(String str)- This constructor constructs a string builder initialised to the contents of the string in the parameters.
StringBuilder Methods
append()- It appends the specified string to the current sequence.
insert()- It inserts the specified string to the specified position in the sequence.
replace()- It replaces the characters in a substring of this sequence with characters in the specified string.
delete()- It removes the characters in a substring of this sequence.
deleteCharAt()- It removes the character at the specified position.
reverse()- It reverses the character’s sequences.
toString()- It returns the string representing the given data.
length()- It returns the string length.
capacity()- It gives the current capacity of a given sequence.
charAt()- It returns the character to a specified position in the sequence.
setCharAt()- It sets a specified character at a specified position in the sequence.
substring()- It returns a new String that contains a subsequence of characters currently contained in this sequence starting from the specified index.
indexOf()- It returns the index within this string of the first occurrence of the specified substring.
lastIndexOf()- It returns the index within this string of the last occurrence of the specified substring
setLength()- It sets the length of the character sequence.
Code Example: The below example demonstrates the usage of the insert() method of StringBuilder in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuilder object with an initial string value
StringBuilder mySb = new StringBuilder("Hero Vide!!");
// inserting different types of data to the StringBuilder class object at a specific index
mySb.insert(10, " Java");
mySb.insert(0, "Welcome, ");
mySb.insert(24, 2024);
// Printing the result from the StringBuilder
System.out.println(mySb);
}
}
Explanation:
In this example, we are using the insert() method to insert the different types of data at a specified position into a StringBuilder and finally printing the results from the StringBuilder.
Output:
Welcome, Hero Vide! Java2024!
Code Example: The below example demonstrates the usage of the toString() method of StringBuilder in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuilder object with an initial string value
StringBuilder mySb1 = new StringBuilder("Hello");
StringBuilder mySb2 = new StringBuilder("Vide, ");
StringBuilder mySb3 = new StringBuilder("Welcome to");
StringBuilder mySb4 = new StringBuilder("Java Course!");
// Converting the StringBuilder to a String
String str1 = mySb1.toString();
String str2 = mySb2.toString();
String str3 = mySb3.toString();
String str4 = mySb4.toString();
// Printing the results from the StringBuilder
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
}
Explanation: In this example, we are using the toString() method to convert the different types of StringBuilders to strings and finally printing the results.
Output:
Hello
Vide,
Welcome to
Java Course!
Code Example: The below example demonstrates the usage of the reverse() method of StringBuilder in Java.
public class Main {
public static void main(String[] args) {
// Creating a StringBuilder object with an initial string value
StringBuilder mySb1 = new StringBuilder("Hello");
StringBuilder mySb2 = new StringBuilder("Vide, ");
StringBuilder mySb3 = new StringBuilder("Welcome to");
StringBuilder mySb4 = new StringBuilder("Java Course!");
// Reversing the StringBuilder object
mySb1.reverse();
mySb2.reverse();
mySb3.reverse();
mySb4.reverse();
// Printing the results from the StringBuilder
System.out.println(mySb1);
System.out.println(mySb2);
System.out.println(mySb3);
System.out.println(mySb4);
}
}
Explanation:
In this example, we are using the reverse() method to reverse the different types of string objects and finally print the reversed strings.
Output:
olleH
,ediV
ot emocleW
!esruoC avaJ
Performance Test between StringBuffer and StringBuilder in Java
To have a better understanding of which class is faster, we have to do a performance test between the StringBuffer and StringBuilder classes in Java. You will notice a great difference between both performances, where StringBuilder will be faster than StringBuffer. It is due to a way because the StringBuffer performs the synchronisation thereby making it slower than StringBuilder.
Let’s see an example now:
Code Example:
public class MyClass {
public static void main(String[] args) {
// Testing a StringBuffer
long startTime = System.currentTimeMillis();
StringBuffer strBuffer = new StringBuffer();
for (int i = 0; i < 100000; i++) {
strBuffer.append("abc");
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken by StringBuffer: " + (endTime - startTime) + "ms"); //Printing the time of execution of StringBuffer with its performance test
// Testing a StringBuilder
startTime = System.currentTimeMillis();
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < 100000; i++) {
strBuilder.append("abc");
}
endTime = System.currentTimeMillis();
System.out.println("Time taken by StringBuilder: " + (endTime - startTime) + "ms"); //Printing the time of execution of StringBuilder with its performance test
}
}
Output:
Time taken by StringBuffer: 21ms
Time taken by StringBuilder: 5ms
Explanation:
By running the above program, we can see how StringBuilder is faster than the StringBuffer. The StringBuilder has taken a time of 5ms while the StringBuffer has taken a time of 21ms.
Conversion from StringBuffer to StringBuilder
You can also convert a StringBuffer to a StringBuilder. Let’s see how to convert the StringBuffer to StringBuilder by using a toString() method available in Java:
public class MyClass {
public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("Hello, I'm HeroVide!");
// Converting the StringBuffer to String
var converted = strBuffer.toString();
// Creating a StringBuilder object
StringBuilder strBuilder = new StringBuilder(converted);
// Displaying the converted StringBuilder
System.out.println("Converted to StringBuilder is: " + strBuilder);
}
}
Explanation:
In this example, we are converting a StringBuffer class to a StringBuilder class using a toString() method of Java. The resulting print statement displays the converted string with the relevant content in it.
Output:
Converted to StringBuilder is: Hello, I'm HeroVide!
Conversion From StringBuilder to StringBuffer
You can also convert a StringBuilder to a StringBuffer. Let’s see how to convert the StringBuilder to StringBuffer by using a toString() method available in Java:
public class MyClass {
public static void main(String[] args) {
// Creating a StringBuilder object
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("Hello, I'm HeroVide!");
// Converting the StringBuilder to String
var converted = strBuilder.toString();
// Creating a StringBuffer object
StringBuffer strBuffer = new StringBuffer(converted);
// Displaying the converted StringBuffer
System.out.println("Converted to StringBuffer is: " + strBuffer);
}
}
Explanation:
In this example, we are converting a StringBuilder class to a StringBuffer class using a toString() method of Java. The resulting print statement displays the converted string with the relevant content in it.
Output:
Converted to StringBuffer is: Hello, I'm HeroVide!
Conclusion
In this blog, we saw the differences between StringBuffer and StringBuilder in Java. Both StringBuffer and StringBuilder classes are used for string manipulation and the choice between them largely depends on the context of use. StringBuffer will be a better option if you need thread safety, synchronisation, etc. StringBuilder is a better choice if you work in a single-threaded environment and need better performance, etc., but no synchronisation.
FAQs
Which one between StringBuffer and StringBuilder should I use for better performance?
For better performance, you should always use the StringBuilder class of Java. It doesn't use synchronisation and works better in a single-threaded environment.
Can I convert a StringBuffer to a StringBuilder?
Yes definitely, you can convert a StringBuffer to StringBuilder and vice versa.
Can StringBuffer and StringBuilder be used interchangeably in code?
While StringBuffer and StringBuilder have similar functionalities, they should not be used interchangeably in specific terms like when in thread safety. Always use StringBuffer when thread safety is your priority and StringBuilder when performance is a more needy task.
Are there any other alternatives to StringBuffer and StringBuilder??
Yes, Java has other string manipulation class options, like StringJoiner, for specific use cases. However, StringBuffer and StringBuilder remain the most widely used and better options for the given tasks.
How do I ensure capacity in StringBuffer and StringBuilder?
While Java provides you with the automatic capacity expansion feature in both StringBuffer and StringBuilder, if you still want to ensure the capacity by yourself, you can use the ensureCapacity() method, which allows you to set the minimum capacity of the buffer. Also, it will give you an increased performance.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.