StringBuffer in Java

The StringBuffer class is similar to String class and something more. The string class creates fixed length  while StringBuffer can create flexible length that can be altered in terms of length and content and also provides ability to modify the actual string.

Let us look at the following example which uses the StringBuffer class to replace the content of StringBuffer object from “Hello word” to “Hello java”.

public class sample
{
            public static void main(String args[])
                        {
                                    StringBuffer sb = new StringBuffer(“Hello word”);
                                    sb.replace(6,10,”java”);
                                    System.out.println(sb);
                        }
}

Output
Hello java

StringBuffer class methods

The following table demonstrates list of methods that can be used for string manipulation.



Method
Meaning
1
StringBuffer append(String st)
Appends the string to the string buffer.
2
StringBuffer delete(int start, int end)
Removes substring starting from start up to end of the string buffer.
3
StringBuffer insert(int pos, String st)
Insert the String into the string buffer
4
StringBuffer replace(int start, int end, String st)
Replace substring starting from start up to end of the string buffer.
5
StringBuffer reverse()
Returns reverse sequence of character of string buffer