Java StringBuffer Class with Example

We have already discussed String in Java many times in our articles and also used them in several java programs. The string is nothing but a collection of characters. Strings in Java play a very important role and learning them thoroughly is one of the essential tasks to become a good Java developer. You must know how to manipulate Strings in different ways. This article will introduce you to the String manipulation in Java which is StringBuffer class which helps to manipulate and perform different operations on Strings in many ways. In this article, we fall into all the methods and constructors of Java StringBuffer class.

Java StringBuffer class

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is StringBuffer in Java?

String in Java is the sequence of characters that has an Immutable attribute. Hence, considering this Java provides a class StringBuffer that gives the facility to create a sequence of characters with mutable (modifiable) attributes. In Java, the class has two main pointers which are used to define a class:

1. Constructor
2. Methods

So, let’s dive deep into the StringBuffer class.

Java StringBuffer Constructors

1. Empty StringBuffer

This constructor creates an empty string buffer with an initial space of 16 characters.

StringBuffer str = new StringBuffer();

2. Argument StringBuffer

This constructor creates a string buffer with a size defined in the argument.

StringBuffer str = new StringBuffer(int size); // it takes an argument in integer.

StringBuffer str = new StringBuffer(20);

3. String StringBuffer in Java

This constructor declares a set of an initial string with 16 characters in a reserved space without reallocation.

StringBuffer str= new StringBuffer(String str); // it takes string as arguments.

StringBuffer str = new StringBuffer(“ContentWriter”);

Java StringBuffer Methods

Methods in Java are the collection of predefined expressions that executes some sort of task when we explicitly call them. Generally to call any of the methods we just execute:

                ReferenceVariable.MethodName(parameters)

Now dive directly to the methods of StringBuffer class:

StringBuffer Methods in Java

1. StringBuffer: length()

It defines the number of characters in the String.

Code to understand the length() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io. * ;
class Main {
  public static void main(String[] args) {
    StringBuffer str = new StringBuffer("ContentWriter");
    int len = str.length();
    System.out.println("Length : " + len);
  }
}

Output:

Length: 13

2. StringBuffer: capacity()

It defines the capacity of the string occupied in the buffer. The capacity method also counts the reserved space occupied by the string.

Code to understand the capacity() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io. * ;
class Main {
  public static void main(String[] args) {
    StringBuffer str = new StringBuffer("ContentWriter");
    int cap = str.capacity();
    System.out.println("Capacity : " + cap);
  }
}

Output:

Capacity: 29

3. StringBuffer: append()

The append() method is used to append the string or number at the end of the string.

Code to understand the append() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io.*;
class Main 
{
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("Tech");
str.append("Vidvan"); // appends a string in the previously defined string.
System.out.println(str);
str.append(0); // appends a number in the previously defined string.
System.out.println(str); 
}
}

Output:

TechVidvanTechVidvan0

4. StringBuffer: insert()

The insert() method is used to insert the string into the previously defined string at a particular indexed position. In the insert method as a parameter, we provide two-argument first is the index and second is the string.

Code to understand insert() method of StringBuffer class:

package com.techvidvan.stringbuffer;
public class StringBufferInsert {
  public static void main(String[] args) {
    StringBuffer stringName = new StringBuffer(" Welcome");
    System.out.println(stringName);
    stringName.insert(8, " to ");
    System.out.println(stringName);
    stringName.insert(12, "TechVidvan ");
    System.out.println(stringName);
    stringName.insert(22, " Tutorial ");
    System.out.println(stringName);
    stringName.insert(31, " of ");
    System.out.println(stringName);
    stringName.insert(35, "Java");
    System.out.println(stringName);
  }
}

Output:

Welcome
Welcome to
Welcome to TechVidvan
Welcome to TechVidvan Tutorial
Welcome to TechVidvan Tutorial of
Welcome to TechVidvan Tutorial of Java

5. StringBuffer: reverse()

The reverse() method reverses all the characters of the object of the StringBuffer class. And, as an output, this method returns or gives the reversed String object.

Code to understand reverse() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.util. * ;
public class StringBufferReverse {
  public static void main(String[] args) {
    StringBuffer stringName = new StringBuffer("Welcome to TechVidvan");
    System.out.println("Original String: " + stringName);
    stringName.reverse();
    System.out.println("Reversed String: " + stringName);
  }
}

Output:

Original String: Welcome to TechVidvan
Reversed String: navdiVhceT ot emocleW

6. StringBuffer: delete()

Let’s move to the next method of the StringBuffer class which is the delete() method. The delete() method deletes a sequence of characters from the StringBuffer object. We provide two arguments to this method in which the first argument is the starting index of the String which we want to delete and the second index the last index of the String up to which we want to delete. Thus, with this method, we can delete or remove a sequence of characters from the string. The output is the characters. String after removing the specified characters.

Syntax:

                         stringName.delete(int startIndex, int endIndex)

Code to understand delete() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io. * ;
public class DeleteMethodDemo {
  public static void main(String[] args) {
    StringBuffer myString = new StringBuffer("TechVidvanJava");
    System.out.println("Original String: " + myString);
    myString.delete(0, 4);
    System.out.println("Resulting String after deleting sequence of characters: " + myString);
  }
}

Output:

Original String: TechVidvanJava
Resulting String after deleting a sequence of characters: VidvanJava

7. StringBuffer deleteCharAt()

The deleteCharAt() method deletes only the character at the specified index. We provide the index number as the argument of the method and it deletes the character present at that index and returns the resulting string after deleting that specific character.

Syntax:

                     stringName.deleteCharAt(int index)

Code to understand deleteCharAt() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io. * ;
public class DeleteCharAtDemo {
  public static void main(String[] args) {
    StringBuffer myString = new StringBuffer("TechVidvanJava");
    System.out.println("Original String: " + myString);

    myString.deleteCharAt(0);
    System.out.println("Resulting String after deleting a character at 0th index: " + myString);

    myString.deleteCharAt(6);
    System.out.println("Resulting String after deleting a character at 6th index: " + myString);
  }

}

Output:

Original String: TechVidvanJava
Resulting String after deleting a character at 0th index: echVidvanJava
Resulting String after deleting a character at 6th index: echVidanJava

8. StringBuffer replace()

The replace() method of the StringBuffer class replaces a sequence of characters with another sequence of characters. It takes three arguments, one is the starting index and the second is the last index, while the last argument is the sequence of characters which we want to replace with the specified characters.

Syntax:

                           stringName.replace(int startIndex, int endIndex, String string)

Code to understand replace() method of StringBuffer class:

package com.techvidvan.stringbuffer;
import java.io. * ;
public class ReplaceMethodDemo {
  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("TechVidvanJava");
    System.out.println("Original String: " + s);
    s.replace(10, 14, "Tutorial");
    System.out.println("Resulting String after replacing: " + s);
  }
}

Output:

Original String: TechVidvanJava
Resulting String after replacing: TechVidvanTutorial

Now we will brief all the other methods of the StringBuffer class with the help of the following table:

S.N. Method  Description
1 char charAt(int index) The charAt() method returns the character present at the specified index.
2 int codePointAt(int index) It returns the Unicode code point of the character at the specified index.
3 int codePointBefore(int index) It returns the Unicode code point) of the character before the specified index
4 int codePointCount(int beginIndex, int endIndex) This method returns the number of Unicode code points in the String between the specified range.
5 void ensureCapacity(int minimumCapacity) This method is used to increase the capacity of the StringBuffer object.
6 void getChars(int sourceBegin, int sourceEnd, char[] destination, int destBegin) This method copies the specified characters in a range to a specific destination character array.
7 int indexOf(String str, int fromIndex) This method returns the index of the first occurrence of the specified substring that starts at the specified index.
8 StringBuffer insert(int offset, String str) This method inserts the string into the specified string.
9 int lastIndexOf(String str) This method returns the index of the last occurrence of the specified substring.
10 void setCharAt(int index, char ch) This method sets a character at the specified index.
11 void setLength(int newLength) This method is used to set the length of the String.
12 String substring(int start, int end) This method returns a new String that starts from the specified index and ends with the specified index.
13 String toString() The toString() method returns data in the form of a string.
14 void trimToSize() This method reduces the storage space of the string.
15 CharSequence subSequence(int start, int end) This method returns a new character sequence from the specified range.

Important Points about StringBuffer class

  • java.lang.StringBuffer class extends from the Object class.
  • Serializable, Appendable, CharSequence are implemented interfaces of StringBuffer class
  • We can use multiple threads safely while using the StringBuffer class. The only condition is that all the methods should be declared as synchronized to work in a multithreaded environment.
  • Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.
  • It inherits some of the methods from Object class which are clone, equals, finalize, getClass, hashCode, notify, notifyAll.

Conclusion

Java StringBuffer class is very useful to perform several operations on the String so that we can manipulate the strings in different ways to get the desired results. The StringBuffer class works more efficiently than the String class. The StringBuffer class has many predefined constructors and methods that help us in manipulating the Strings. In this article, we studied many stringbuffer methods in java like insert, delete, replace, length, capacity, append, etc with explanations and proper examples. All other methods are summarized in the table.

We hope this article will surely help you understand the StringBuffer class.

Do not forget to share your feedback in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.