Introduction

A StringBuffer represents a string that can be modified. Whenever there is a concatenation operator (+) used with strings, a StringBuffer object is automatically created.

Constructors used of StringBuffer

Following constructors are used for StringBuffer class:

Methods Used with StringBuffer

The commonly used methods of the StringBuffer class are summarized:

Immutability

String in Java, once created, cannot be changed directly. This is called immutability in strings. To overcome this, Java provides the StringBuffer class, which represents a mutable sequence of characters. StringBuffer is a peer class of String and represents a growable and writable character sequence. These sequences may have characters inserted in the center or appended at the end. The concept of immutability is defined in the given example below:

Source Code

class StringBuf {
    protected StringBuf() {}
    public static void main(String args[]) {
        StringBuffer buf = new StringBuffer("Java");
        //appended
        buf.append(" Guide ver 1/");
        buf.append(3); // append Java Guide ver 1/3
        int index = 5;
        buf.insert(index, "Student "); // Set Java Student Guide Ver1/3
        index = 23;
        buf.setCharAt(index, '.');
        Set Java Student Guide Ver1 .3
        int start = 24;
        int end = 25;
        buf.replace(start, end, "4"); //replace Java Student Guide Ver 1.4
        String s = buf.toString(); //Convert to String
        System.out.println(s);
    }
}

Output

Summary

A StringBuffer represents a string that can be modified. StringBuffer insert(String s), StringBuffer reverse(), StringBuffer replace(int start, int end, String s), are a few of the functions used in the StringBuffer class. Java provides the StringBuffer class, which represents a mutable sequence of characters. StringBuffer is a peer class of String and represents growable and writable character sequence. These sequences may have characters inserted in the center or appended at the end.