// To create an empty StringBuffer with a default initial capacity of 16 characters
StringBuffer sb = new StringBuffer();
// To create a StringBuffer from a String
StringBuffer sb = new StringBuffer(“Merit Campus”);
// To create an empty StringBuffer with an initial capacity of 100 characters
StringBuffer sb = new StringBuffer(100);
Now let us look at the following program and learn some of the methods of StringBuffer class :
public static void main(String arg)
StringBuffer sb = new StringBuffer("Merit Campus");
sb.setCharAt(5, '*'); //LINE A
StringBuffer sb1 = new StringBuffer("C++,Html,C");
sb1.replace(4, 8,"Java"); //LINE B
StringBuffer sb2 = new StringBuffer("Merit");
In the above program, we initially created an instance of the
StringBuffer class to hold the sequence of characters "
Merit Campus". To replace any single character of the string, we can use
setCharAt method which is shown in
LINE A. To replace a sequence of characters,
replace method can be used as shown in
LINE B. To add characters at the end of the string, append method can be used and to insert characters in between the string
insert method can be used. All these methods are available in different versions to enable us to add different types of data (
String…). A version of
insert is shown above, which inserts specified character at specified position.
- Can use objects of
StringBuffer class instead of
String class, in situations where contents of the string change frequently.
StringBuffer is thread-safe. There is a class by name StringBuilder Class In Java that has same methods as that of
StringBuffer but it is not thread-safe. Use of
StringBuilder is recommended over
StringBuffer for better performance when thread-safety is not needed.