StringBuffer in Java

Profile picture for user arilio666

This article will show a string buffer similar to a string builder. Here is the comparison article about both of them https://www.programsbuzz.com/interview-question/difference-between-string-stringbuffer-and-stringbuilder-java

In Java, StringBuffer is a class used to create and manipulate mutable (modifiable) sequences of characters.  It is similar to the String class, but with one crucial difference: StringBuffer objects can be modified, while String objects cannot be changed once created.

They are mutable, meaning that we can modify the contents of the buffer without the need for a new object. The initial capacity of the string buffer can be specified when it is created. This can also be done later too using the ensureCapacity() method.

Let us see some of the critical features of StringBuffer:

Append: The append() method adds characters, strings, and objects to the buffer's end.

   StringBuffer sb = new StringBuffer();
       sb.append("John");
       sb.append(" ");
       sb.append("Wick");
       String message = sb.toString();
       System.out.println(message);
        

Output:

John Wick

Insert: Inserts string at the given position.

 StringBuffer sb = new StringBuffer("John ");
       sb.insert(1, "Wick");
       System.out.println(sb);

Output:

JWickohn

Replace: Replace the string provided with the beginning and end index.

StringBuffer sb = new StringBuffer("John");
       sb.replace(1, 3, "Wick");
       System.out.println(sb);
        

Output:

JWick

Delete: Deletes string provided with the begin and end index.

  StringBuffer sb = new StringBuffer("Hello");
       sb.delete(1, 3);
       System.out.println(sb);
        

Output:

Hlo

Reverse: Reverses the current string.

 StringBuffer sb = new StringBuffer("John");
       sb.reverse();
       System.out.println(sb);
        

Output:

nhoJ

Conclusion:

These are some of the methods used commonly in StringBuffer.

Tags