StringBuffer Class


The StringBuffer class in Java is used to represent a mutable sequence of characters. Unlike the String class, the StringBuffer class can be modified after it is created. The class provides a number of useful methods to perform various operations on strings. Here are some common methods of the StringBuffer class:

  1. append(String str): Appends the specified string to the end of the buffer.

  2. insert(int offset, String str): Inserts the specified string into the buffer at the specified offset.

  3. delete(int start, int end): Deletes the characters in the buffer between the start and end indices.

  4. reverse(): Reverses the characters in the buffer.

  5. capacity(): Returns the current capacity of the buffer.

  6. ensureCapacity(int minimumCapacity): Ensures that the buffer has at least the specified minimum capacity.

  7. length(): Returns the length of the buffer.

  8. setCharAt(int index, char ch): Sets the character at the specified index to the specified value.

  9. substring(int start, int end): Returns a new string that is a substring of the buffer.

  10. toString(): Returns the string representation of the buffer.


public class StringBufferExample {
    public static void main(String[] args) {
        // Create a StringBuffer object
        StringBuffer sb = new StringBuffer("Hello");
        System.out.println("StringBuffer is: " + sb);

        // Append a string to the StringBuffer
        sb.append(" World");
        System.out.println("Appended StringBuffer is: " + sb);

        // Insert a string at a particular position in the StringBuffer
        sb.insert(5, ", ");
        System.out.println("Inserted StringBuffer is: " + sb);

        // Replace a substring in the StringBuffer with another substring
        sb.replace(6, 11, "Java");
        System.out.println("Replaced StringBuffer is: " + sb);

        // Delete a substring from the StringBuffer
        sb.delete(0, 6);
        System.out.println("Deleted StringBuffer is: " + sb);

        // Reverse the order of the characters in the StringBuffer
        System.out.println("Reversed StringBuffer is: " + sb);