StringBuffer Java – StringBuffer class and methods with examples  


Java StringBuffer

StringBuffer class in Java  

The StringBuffer in Java is a class that we can use to manipulate Strings. Strings are immutable which means it is of fixed length whereas StringBuffer is mutable and growable meaning we can change the length of string and do different manipulations like append, delete, insert, etc. In this tutorial, we will discuss the StringBuffer class in Java and methods in detail with examples. We will also see the difference between StringBuffer vs StringBuilder towards the end of the tutorial.

Stringbuffer in JavaPin

Features  

Below are the features of the StringBuffer class:

  • It creates a mutable String object
  • It is thread-safe and synchronized which means we can use it for multithreading.
  • Implements the CharSequence, Appendable, and Serializable interfaces.
  • Inherits all the methods from the Object class.

Constructors  

The StringBuffer class contains the below constructors:

Please click Like if you loved this article?

ConstructorDescription
StringBuffer()Creates an empty default constructor with initial capacity as 16
StringBuffer(CharSequence csq)Creates a StringBuffer with the characters in the specified CharSequence. The capacity is 16 plus the length of the characters in the argument
StringBuffer(int initialCapacity)Creates an empty StringBuffer with the specified capacity
StringBuffer(String str)Creates a StringBuffer with the specified string. The capacity is 16 plus the length of the string argument
See also
Operators in Java

StringBuffer methods in Java  

Below are the StringBuffer methods

MethodsDescription
StringBuffer append(String s)Appends the specified string to the original string
StringBuffer append(CharSequence csq, int start, int end)Appends the specified portion of the character sequence to the original string
int capacity()Returns the current capacity of the StringBuffer
char charAt(int index)Returns the character at the specified index position
int codePointAt(int index)Returns the codepoint character at the specified index
StringBuffer delete(int start, int end)Deletes the characters from the StringBuffer starting form the specified start index to end index
StringBuffer deleteCharAt(int index)Deletes the character at the specified index
void ensureCapacity(int capacity)Ensures that the StringBuffer has the minimum specified capacity
int indexOf(String str)Returns the index of the specified substring present in the string
StringBuffer insert(int offset, String str)Inserts the specified string at the specified index
int lastIndexOf(String str)Returns the index of the last occurrence of the specified substring
int length()Returns the number of characters of the string
StringBuffer replace(int start, int end, String str)Replaces the substring with the specified string starting from the start index till the end index
StringBuffer reverse()Reverses the characters in the specified string
void setCharAt(int index, char ch)Sets the specified character at the specified index in the input string
void setLength(int newLength)Sets the new length of the character string
String subString(int start, int end)Returns a substring of the string starting from the specified start index to end index
String toString()Returns the string representation of the StringBuffer object
void trimToResize()Trims the storage size of the CharacterSequence
See also
How to limit decimal places in Java

StringBuffer examples  

Let’s see various examples by using different StringBuffer methods.

Example: insert() method – Java StringBuffer class

We can use the insert() method to insert a new string at the required index position. In the below example, it inserts the new string at position 4 hence prints the output as “Javalanguage”.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Java");
    s.insert(4, "language");
    
    System.out.println(s);
  }

}
Javalanguage

Example: append() method – Java StringBuffer class

The append() method of the StringBuffer class in Java appends or concatenates the specified string to the original string.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Java");

    s.append("programming");
    
    System.out.println(s);
  }

}
Javaprogramming

Example: replace() method – Java StringBuffer class

The replace() method of the Java StringBuffer class replaces the string with the new string from the given offset position. In this example, it replaces the characters from position 0 to 2 with the new string. Hence the characters ‘Ja’ are replaced with the text “Hello”.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Java");

    s.replace(0, 2, "Hello");
    
    System.out.println(s);
  }

}
Hellova

Example: delete() and deleteCharAt() method

The delete() method deletes the character from the specified start position till the end index. We can also delete a character at the specified index using the deleteCharAt() method.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Java langauge");
    
    s.delete(1, 2);
    System.out.println("Output after delete: " + s);
    s.deleteCharAt(6);
    System.out.println("Output after deleteCharAt: " + s);
  }

}
Output after delete: Jva langauge
Output after deleteCharAt: Jva lagauge

Example: reverse() method – StringBuffer

The reverse method reverses the characters in the string as you can see in the below example.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Java");
    System.out.println("Original string: " + s);
    s.reverse();
    System.out.println("Reversed string: " + s);
    
  }

}
Original string: Java
Reversed string: avaJ

Example: capacity() method – StringBuffer

The capacity method calculates the capacity of the StringBuffer object which means how many characters it can store. By default, the capacity is 16 after it which increases by ((old_capacity*2)+2) which means 16*2+2 = 34.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer();
    
    System.out.println("Default capacity: " + s.capacity());
    s.append("Welcome");
    System.out.println("Current capacity: " + s.capacity());
    s.append(" to Java tutorial");
    System.out.println("New capacity: " + s.capacity());
    System.out.println("String: " + s);
    
  }

}
Default capacity: 16
Current capacity: 16
New capacity: 34
String: Welcome to Java tutorial

Example: subString() method

The subString() method of the StringBuffer class retrieves a portion of the string based on the start or end index. In the below example, the first output retrieves the substring based on only the start index and hence it prints the string from the 5th character. The second output retrieves the substring based on the start and end index and hence prints the string between the 5th and 10th index.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Welcome to Java tutorial");
    System.out.println("Original string: " + s);
    System.out.println("Substring with start index: " + s.substring(5));
    System.out.println("Substring with start and end index: " + s.substring(5, 10));
  }

}
Original string: Welcome to Java tutorial
Substring with start index: me to Java tutorial
Substring with start and end index: me to

Example: Other methods of Java StringBuffer

There are other methods that are part of the StringBuffer class in Java. For example, charAt() returns the character at the specified index, indexOf() returns the index of the specified string, lastIndexOf() returns the index of the last occurrence of the specified string, length() returns the length of the input string.

See also
How to compile and run Java program

We can also set a new character at the specified index using the setCharAt() method and set a new length using the setLength() method.

public class StringBufferDemo {

  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Welcome to Java tutorial");
    
    System.out.println("Character at index 4: " + s.charAt(4));
    System.out.println("Index of string: " + s.indexOf("to"));
    System.out.println("Last index of string: " + s.lastIndexOf("Java"));
    System.out.println("Length of the string: " + s.length());
    
    s.setCharAt(1, 'a');
    System.out.println(s);
    s.setLength(30);
    System.out.println("New length: "  + s.length());
    
  }

}
Character at index 4: o
Index of string: 8
Last index of string: 11
Length of the string: 24
Walcome to Java tutorial
New length: 30

StringBuffer vs StringBuilder  

Below are the differences between Java StringBuffer and StringBuilder

StringBufferStringBuilder
Introduced during the first release of JavaIntroduced in Java 5
It is synchronizedIt is non-synchronized
Less efficientMore efficient
It is thread-safeIt is not thread-safe
Performance is slowPerformance is faster

StringBuffer vs StringBuilderPin

Reference

Please click Like if you loved this article?

1