Last Updated on July 3, 2023 by Mayank Dham
StringBuffer in Java provides a convenient and efficient way to manipulate strings in Java and is widely used for string-related operations in many applications. StringBuffer in Java provides a variety of methods to efficiently perform operations such as concatenating strings, inserting characters, and removing characters.
What is StringBuffer in Java?
If we take the example of the string "PrepBytes," which is stored as a String variable, and we intend to add multiple characters to it, we encounter a limitation. Each time we add characters to the String, a new memory allocation is created for the modified String, resulting in no modification to the original String itself.
This wastes a lot of memory, but when we store the String in the StringBuffer class, no new memory is allocated. StringBuffer objects are like String class objects, but they can be modified to perform manipulating operations on the StringBuffer. This attribute of the StringBuffer in Java is known as "mutable."
String s = new String("Prep"); //Current String
s+="Bytes"; //Adding new String cause new memory allocation for the String
Adding the String to an existing StringBuffer sequence using the append() method, on the other hand, will not allocate new memory for storing new sequences.
As a result, the StringBuffer class is often used when dealing with various types of String operations. In addition, the StringBuffer object is thread-safe, which means that multiple threads cannot access the StringBuffer object in Java.
To put it simply, we cannot do many operations at the same time. Let us now look at the StringBuffer Syntax in Java.
Syntax of StringBuffer Class in Java
The syntax of the StringBuffer class in Java is as follows:
public class StringBuffer
extends Object
implements Serializable, CharSequence
The StringBuffer class provides methods for constructing and manipulating strings that can be changed. It is similar to StringBuilder, but StringBuffer is thread-safe (i.e., it synchronizes all its methods).
Example of Creating StringBuffer Object
//Declaring the StringBuffer class.
StringBuffer PrepBuddy = new StringBuffer(); //PrepBuddy is the reference of StringBuffer class.
The StringBuffer class includes several constructors for various operations.
Let’s have a look at the StringBuffer class’s constructors.
Constructors of StringBuffer Class in Java
Let’s go over the various StringBuffer Constructors in Java one by one:
-
StringBuffer(): This constructor is used to make a StringBuffer with no characters and a capacity of 16 bytes at the start. Capacity is defined as the maximum number of elements that the StringBuffer object can store. This constructor has no parameters.
Syntax of StringBuffer:
StringBuffer Buddy = new StringBuffer();
-
StringBuffer(int capacity): This constructor is used to set the initial size of the StringBuffer. This constructor accepts one parameter.
Syntax of StringBuffer(int capacity):
StringBuffer PrepBuddy = new StringBuffer(12);
-
StringBuffer(String str): This constructor takes as an input a String and turns it to a StringBuffer object. StringBuffer’s default capacity is 16 bytes.
Syntax of StringBuffer(String str):
StringBuffer PrepBuddy = new StringBuffer(String str);
-
StringBuffer(Char Sequence): This constructor is used to create a StringBuilder of charsequence. The charsequence is the order in which the characters appear.
Syntax of StringBuffer(Char Sequence):
StringBuffer PrepBuddy = new StringBuffer(CharSequence);
Commonly used Methods of StringBuffer Class
Below are some of the most commonly used methods of the StringBuffer class in Java
1. append(String str): appends the specified String to the end of this StringBuffer.
Example of append(String str):
import java.io.* ; class Main { public static void main(String args[]) { StringBuffer str = new StringBuffer("Prep "); str.append("Bytes"); // now original string is changed System.out.println(str); } }
Output:
PrepBytes
2. insert(int index, String str): inserts the specified String at the specified index in this StringBuffer.
Example of insert(int index, String str):
import java.io.* ; class Main { public static void main(String args[]) { StringBuffer str = new StringBuffer("Bytes "); str.insert(1, "Java"); // Now original string is changed System.out.println(str); } }
Output:
BJavaytes
3. delete(int start, int end): removes the characters in this StringBuffer in the specified range (from start to end-1).
Example of delete(int start, int end):
import java.io.* ; class Main { public static void main(String args[]){ StringBuffer str = new StringBuffer("PrepBytes"); str.delete(1,4); System.out.println(str); } }
Output:
PBytes
4. replace(int start, int end, String str): replaces the characters in this StringBuffer in the specified range (from start to end-1) with the specified String.
Example of replace(int start, int end, String str):
import java.io.* ; class Main{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("PrepBytes"); sb.replace(1,4,"Java"); System.out.println(sb); } }
Output:
PJavaBytes
5. reverse(): reverse the order of characters in this StringBuffer.
Example of reverse():
import java.io.* ; class Main { public static void main(String args[]) { StringBuffer str = new StringBuffer("PrepBytes"); str.reverse(); System.out.println(str); } }
Output:
setyBperP
6. length(): returns the length (number of characters) in this StringBuffer.
Example of length():
import java.io.* ; class Main { public static void main(String args[]) { StringBuffer str = new StringBuffer("PrepBytes"); System.out.println(str.length()); } }
Output:
9
7. capacity(): This method returns the current capacity of the StringBuffer object.
Example of capacity():
import java.io.* ; class Main { public static void main(String args[]) { StringBuffer str = new StringBuffer(); System.out.println( str.capacity() ); } }
Output:
16
Please keep in mind that the empty constructor saves space for 16 characters. As a result, the result is 16.
Conclusion
StringBuffer in Java provides a powerful tool for manipulating strings efficiently. It allows for dynamic modification of strings by offering methods for appending, inserting, and deleting characters. With its ability to perform in-place modifications, StringBuffer in Java is particularly useful when dealing with large or frequently changing strings.
Frequently Asked Questions (FAQs)
Here are some frequently asked questions about the StringBuffer in Java:
Question-1 What is the difference between String and StringBuffer in Java?
Ans – The main difference between the String and StringBuffer classes in Java is that the String class is immutable, while the StringBuffer class is mutable. Once you create a String object, its value cannot be changed, while a StringBuffer object can be changed after it has been created.
Question-2 When should you use StringBuffer in Java?
Ans – You should use the StringBuffer class in Java when you need to make multiple changes to a string, or when you are building up a large string from multiple smaller strings. The StringBuffer class is more efficient for these use cases than the String class, which requires the creation of a new String object each time you make a change to the string.
Question-3 Is StringBuffer thread-safe in Java?
Ans – Yes, the StringBuffer class in Java is thread-safe, which means that it can be safely used in multithreaded environments.
Question-4 What is the performance difference between String and StringBuffer in Java?
Ans – The StringBuffer class is generally faster than the String class when you are making multiple changes to a string. This is because the StringBuffer class is optimized for these use cases, while the String class is optimized for the case where the string is never changed after it has been created.
Question-5 Can you convert a StringBuffer to a String in Java?
Ans – Yes, you can convert a StringBuffer to a String in Java using the toString() method. The toString() method returns the contents of the StringBuffer as a String object.