StringBuilder 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 class from the java.lang package.

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

What is the StringBuilder class in Java?

StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

How to create a StringBuilder object in Java?

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

Example:

 
// creates an empty string Builder with the initial capacity of 16.
 StringBuilder str = new StringBuilder();

 // creates a string Builder with the specified string.
 StringBuilder str = new StringBuilder("some string value");

 // creates an empty string Builder with the specified capacity as length.
 StringBuilder str = new StringBuilder(10);
 


Most used methods of StringBuilder class with examples:

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

class Test {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Java ");
    
    sb.append("Programming"); // original string is changed
    
    System.out.println(sb);
  }
}
Output: Java Programming
 
Method: StringBuilder 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) {
    
    StringBuilder sb = new StringBuilder("Java  Programming");
        
    sb.insert(5, "alegru "); //inserts the specified string at index 5
        
    System.out.println(sb);
  }
}
Output: Java alegru Programming
 
Method: StringBuilder 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) {
    StringBuilder sb = new StringBuilder("Programming");
        
    sb.replace(2, 5, "Java");
        
    System.out.println(sb);
  }
}
Output: PrJavaamming
 
Method: StringBuilder 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) {
    StringBuilder sb = new StringBuilder("Programming");
        
    sb.delete(1,3);
        
    System.out.println(sb);
  }
}
Output: Programming
 
Method: StringBuilder reverse()
Description: It is used to reverse the string.
Example:
class Test {

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

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(); // 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: 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) {
    StringBuilder sb = new StringBuilder(); // 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: void setCharAt(int index, char c)
Description: Replaces the specified character(s) in this string.
Example:
class Test {

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

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

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

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

Leave a Reply

Your email address will not be published.