StringBuffer class in Java

We learned so far that String is immutable, meaning that the String object’s content can not be changed once it is created.

When we perform some operations on a String, this will create a new String object. If we really want to modify the String, we will use the StringBuilder or StringBuffer classes from java.lang package.

Also, you might be interested in checking out the StringBuilder class and the differences between StringBuilder and StringBuffer

What is the StringBuffer class in Java?

StringBuffer objects are like String objects, except that they can be modified.

The StringBuffer class is very similar to the StringBuilder class, except that the StringBuffer is thread-safe i.e. multiple threads cannot access it simultaneously.

How to create a StringBuffer object in Java?

We create a StringBuffer object by instantiating it with the keyword new, just like any other class in Java.

Example:

 // creates an empty string buffer with the initial capacity of 16.
 StringBuffer str = new StringBuffer();
 
 // creates a string buffer with the specified string.
 StringBuffer str = new StringBuffer("some string value");
 
 // creates an empty string buffer with the specified capacity as length.
 StringBuffer str = new StringBuffer(10);


Most used methods of StringBuffer class with examples:

Method: synchronized StringBuffer append(String s)
Description: Appends the specified string with this string.
Example:

class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java ");
    
    sb.append("Programming"); // original string is changed
    
    System.out.println(sb);
  }
}
Output: Java Programming
 
Method: synchronized StringBuffer insert(int offset, String s)
Description: Inserts the specified string with this string at the specified position. 
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java  Programming");
        
    sb.insert(5, "alegru "); //inserts the specified string at index 5
        
    System.out.println(sb);
  }
}
Output: Java alegru Programming
 
Method: synchronized StringBuffer replace(int startIndex, int endIndex, String str)
Description: It is used to replace the string from specified startIndex and endIndex.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Programming");
        
    sb.replace(2, 5, "Java");
        
    System.out.println(sb);
  }
}
Output: PrJavaamming
 
Method: synchronized StringBuffer delete(int startIndex, int endIndex)
Description: It is used to delete the string from specified startIndex and endIndex.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Programming");
        
    sb.delete(1,3);
        
    System.out.println(sb);
  }
}
Output: Pgramming
 
Method: synchronized StringBuffer reverse()
Description: It is used to reverse the string.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java Programming");
        
    sb.reverse();
        
    System.out.println(sb);
  }
}
Output: gnimmargorP avaJ
 
Method: synchronized int capacity()
Description: Returns the current capacity. 
Take a look at the comments to better understand the capacity in the StringBuffer class.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer(); // The initial capacity is 16

    System.out.println("The initial capacity is: " + sb.capacity());

    sb.append("Java");

    System.out.println("Current capacity is: " + sb.capacity()); 

    // Capacity is still 16
    sb.append(" Programming Language");

    // with this, we exceed the initial capacity and it increases according to this principle: (oldCapacity * 2) + 2
    System.out.println("Current capacity is: " + sb.capacity()); // Now current capacity is ((16 * 2) + 2) = 34
  }
}
Output: The initial capacity is: 16 Current capacity is: 16 Current capacity is: 34
 
Method: synchronized void ensureCapacity(int minimumCapacity)
Description: It is used to ensure the capacity is at least equal to the given minimum.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer(); // Initial capacity is 16
    System.out.println("The initial capacity is: " + sb.capacity());
    sb.ensureCapacity(50);
    System.out.println("Current capacity: " + sb.capacity());
  }
}
Output: The initial capacity is: 16 Current capacity: 50
 
Method: synchronized void setCharAt(int index, char c)
Description: Replaces the specified character(s) in this string.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Hello World.");
    sb.setCharAt(1, 'A');
    System.out.println(sb);
  }
}
Output: HAllo World.
 
Method: synchronized String substring(int beginIndex)
Description: Returns the substring from the specified beginIndex.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java Programming");
    System.out.println(sb.substring(5));
  }
}
Output: Programming
 
Method: synchronized String substring(int beginIndex, int endIndex)
Description: Returns the substring from the specified beginIndex and endIndex.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java Programming");
    System.out.println(sb.substring(5, 12));
  }
}
Output: Program
 
Method: synchronized StringBuffer delete(int start, int end)
Description: Deletes the subsequence from start to end-1 (inclusive) in the StringBuffer’s char sequence.
Example:
class Test {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Java Programming");
    sb.delete(2, 8);
    System.out.println(sb);
  }
}
Output: Jagramming
 
Method: synchronized StringBuffer deleteCharAt(int index)
Description: Deletes the character located at the given index.
Example:
class Test {

    public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Java Programming");
      sb.deleteCharAt(4);
      System.out.println(sb);
  }
}
Output: JavaProgramming
 
That’s it!

 

Leave a Reply

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