StringBuilder in Java – StringBuilder class and methods using StringBuilder Java with examples


Java StringBuilder

StringBuilder in Java

StringBuilder class in Java is used to manipulate strings so that we can modify the value. In other, StringBuilder class is mutable. It is similar to StringBuffer and String class except that this is mutable whereas StringBuffer is immutable. The performance of StringBuilder is faster than StringBuffer and does not support multiple threads and hence is non-synchronized. In this tutorial, we will learn about the StringBuilder class and methods like append, reverse, delete,toString etc using StringBuilder Java with examples.

StringBuilder in JavaPin

Constructors of Java StringBuilder

Below are the constructors of the StringBuilder class:

ConstructorDescription
StringBuilder()Creates an empty StringBuilder with default capacity as 16
StringBuilder(String str)Creates a StringBuilder object initialized with the specified string.
StringBuilder(int length)Creates an empty StringBuilder with the specified length
StringBuilder(CharSequence csq)Creates a StringBuilder object with the specified character sequence

Methods of StringBuilder class in Java

Below are the StringBuilder methods:

MethodsDescription
StringBuilder append(String str)Appends the specified string to the StringBuilder object
int capacity()Returns the current capacity of the String object
char charAt(int index)Returns the character present in the string at the specified index
int compareTo(StringBuilder another)Compares two StringBuilder objects lexicographically
StringBuilder delete(int start, int end)Removes the substring based on the specified start and end index from the StringBuilder object
StringBuilder deleteCharAt(int index)Removes the character at the specified index from the StringBuilder object
void ensureCapacity(int minCapacity)Ensures that the StringBuilder has the specified minimum capacity
int indexOf(String str)Returns the index of the specified string
StringBuilder insert(int offset, String str)Inserts the specified string at the specified offset position
int lastIndexOf(String str)Returns the index of the last occurrence of the specified string
int length()Returns the length of the CharSequence
StringBuilder replace(int start, int end, String str)Replaces the string value with the specified string starting from the specified start index upto the end index
StringBuilder reverse()Reverses the string present in the StringBuilder object
void setCharAt(int index, char c)Sets the specified character at the specified index
void setLength(int newLength)Sets the specified new length of the StringBuilder object
String subString(int start)Returns the substring portion from the specified start position
String subString(int start, int end)Returns the substring portion ranging between the specified start and end index
String toString()Returns the String representation of the object
void trimToSize()Attempts to reduce the storage size of the StringBuilder object
See also
ScheduledExecutorService in Java

Java StringBuilder Examples

In this section, we will see about the StringBuilder Java class and methods using StringBuilder Java with examples.

Example: insert() method

We can insert a specified string at the required position using the StringBuilder Java method which is insert(). The below example inserts the new string at index 2.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Java");
    sb.insert(2, "Hello");
    
    System.out.println(sb);

  }

}
JaHellova

Example: append() method

The StringBuilder append method in Java appends the new string to the existing string at the end. In this example, we add a new string “language” to the existing string “Java”. Hence the output is “Java language”

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Java");
    sb.append(" language");
    
    System.out.println(sb);

  }

}
Java language

Example: reverse() method

The below example shows how to use the StringBuilder reverse method. This method returns a reversed string.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Java");
    
    sb.reverse();
    System.out.println(sb);

  }

}
avaJ

Example: replace() method

The replace method replaces the characters with the new string starting from the specified index. In this example, it replaces the characters from index 2 to 4 with the new string.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");
    
    sb.replace(2, 4, "Hello");
    System.out.println(sb);

    
  }

}
WeHelloome to Java tutorial

Example: delete() method

The StringBuilder delete method deletes the characters from the specified start index until the end index. We can also delete a single character at the specified index using the deleteCharAt() method. The below example illustrates both the delete methods.

See also
How to compile and run Java program
public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");

    sb.delete(2, 8);
    System.out.println("String after delete operation: " + sb);
    sb.deleteCharAt(15);
    System.out.println("String after deleteCharAt operation: " + sb);
    
  }

}
String after delete operation: Weto Java tutorial
String after deleteCharAt operation: Weto Java tutoral

Example: subString() method

The Java subString() method returns the portion of the string based on the specified index. In the below example, the first output returns the substring from index 5 and the second output returns the substring ranging between index 5 and 10.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");
    
    System.out.println("Substring from index 5: " + sb.substring(5));
    System.out.println("Substring ranging between index 5 and 10: " + sb.substring(5, 10));
    
  }

}
Substring from index 5: me to Java tutorial
Substring ranging between index 5 and 10: me to

Example: toString() method

The Java StringBuilder toString method returns the String representation of the specified object.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");
    
    String s = sb.toString();
    System.out.println("String representation: " + s);
    
  }

}
String representation: Welcome to Java tutorial

Example: length() method

We can use the length() method to calculate the StringBuilder size of the string. We can also set the new size of the StringBuilder object using the setLength() method.

public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");
    
    System.out.println("Size of string: " + sb.length());
    sb.setLength(50);
    System.out.println("New size of the string: " + sb.length());
    
  }

}
Size of string: 24
New size of the string: 50

Example: Other methods

Below is an example of other methods of the StringBuilder class. The charAt() method returns the character at the specified index. The indexOf() method returns the index of the first occurrence of the specified string. The lastIndexOf() method returns the index of the last occurrence of the specified string.

See also
EnumMap in Java
public class StringBuilderDemo {

  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Welcome to Java tutorial");
  
    System.out.println("Original string: " + sb);
    System.out.println("Char at index 3: " + sb.charAt(3));
    System.out.println("Index of string 'to' : " + sb.indexOf("to"));
    System.out.println("Last index of string 'to' : " + sb.lastIndexOf("to"));

    
  }

}
Original string: Welcome to Java tutorial
Char at index 3: c
Index of string 'to' : 8
Last index of string 'to' : 18

 

Reference

1