DEV Community

Ezhil Abinaya K
Ezhil Abinaya K

Posted on

StringBuffer in Java

StringBuffer
StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.
append(char c)
It appends the string representation of the char argument to this sequence.

public class StringBufferDemo {
    public static void main(String[] args){

        // Creating StringBuffer
        StringBuffer s = new StringBuffer();

        // Adding elements in StringBuffer
        s.append("Hello");
        s.append(" ");
        s.append("world");

        // String with the StringBuffer value
        String str = s.toString();
        System.out.println(str);
    }
}
//Hello world
Enter fullscreen mode Exit fullscreen mode

insert() Method
insert() method inserts the given string with this string at the given position.

 s.insert(1, "Java");
 System.out.println(s); // HJavaello world
Enter fullscreen mode Exit fullscreen mode

replace()
replace() method replaces the given string from the specified beginIndex and endIndex-1.

   StringBuffer sb = new StringBuffer("Hello");
        sb.replace(1, 3, "i"); 
        System.out.println(sb);
//Hilo
Enter fullscreen mode Exit fullscreen mode

delete()
delete() method is used to delete the string from the specified beginIndex to endIndex-1.

sb.delete(1, 3);
 System.out.println(sb);//Ho
Enter fullscreen mode Exit fullscreen mode

reverse()
reverse() method of the StringBuffer class reverses the current string.

sb.reverse();
 System.out.println(sb);//oH
Enter fullscreen mode Exit fullscreen mode

Reference
https://www.geeksforgeeks.org/java/stringbuffer-class-in-java/
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html

Top comments (0)