Latest Code Tutorials

StringBuilder Class in Java Example | Java StringBuilder Class


Java StringBuilder class is an inbuilt class that is used to create a modifiable, i.e., mutable string (unlike the String class which provides immutable strings). The StringBuilder class is used to represent the collection/sequence of characters. The StringBuilder class is similar to the StringBuffer class, except that the StringBuilder class is non-synchronized and StringBuffer is synchronized. When there is only a single thread (i.e., the program is not multi-threaded), the StringBuilder class has an advantage over the StringBuffer class being faster than it.

StringBuilder Class in Java

The StringBuilder class is available since JDK 1.5. It can be imported from the java.lang package. Java StringBuilder class is also used to create the mutable (modifiable) string object.

StringBuilder class provides the API compatible with StringBuffer, but with no guarantee of synchronization. StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the single thread was using the string buffer.

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under the most implementations.

Instances of StringBuilder are not safe for use by the multiple threads. If such synchronization is required, then it is recommended that StringBuffer be used.

See the following diagram.

StringBuilder Class in Java

#Constructors of StringBuilder Class

See the following constructors method.

  1. StringBuilder(): Creates a StringBuilder with default capacity (that is 16) and no characters in it.
    • capacity: The initial memory allocated to the StringBuilder. Having initial capacity as 16 means that the memory to store 16 characters is allocated to the StringBuilder.
  2. StringBuilder(int cap): Creates an empty StringBuilder with initial capacity equals to cap.
  3. StringBuilder(String s): Creates a StringBuilder having the content of String s.
  4. StringBuilder(CharSequence s): Creates a StringBuilder with the content of CharSequence s.


When the length of StringBuilder exceeds its capacity, then memory allocation is done. The rule of this allocation is: if the new_length is less than or equal to 2*(capacity+1).

then new_capacity = 2*(capacity+1)

else, new_capacity = new_length

Two StringBuilder objects can never be equal, therefore for comparing them, first convert them to String objects and then use equals() method.

#Methods of StringBuilder Class

int length():

It tells the current length of the StringBuilder (not the capacity).

int capacity(): 

It tells the current capacity of the StringBuilder. Capacity will always be greater than or equal to the length of StringBuilder.

void ensureCapacity(int cap):

It is used to set the minimum capacity of StringBuilder equals to the cap. 

void setLength(int len):

It sets the length of the StringBuilder. Here the length specifies the length of the buffer. When we increase the size of the buffer, null characters are added to the end of the existing buffer. And if the specify a length less than the current length, then characters beyond the new length get deleted.

void getChars(int start, int end, char target[], int targetStart):

It copies a substring of the StringBuilder into a character array. Int targetStart specifies the position in the array from which the characters of substring start storing.

char charAt(int i):

It returns the value of the character stored on the ith index in the StringBuilder.

void setCharAt(int i, char c):

It sets the value of a character on the ith index in the StringBuilder.

StringBuilder append(String str):

It concatenates the string str at the end of StringBuilder.

StringBuilder append(int num):

It concatenates the string format of int num at the end of StringBuilder.

StringBuilder append(Object o):

It concatenates the string representation of Object o at the end of StringBuilder.

StringBuilder appendCodePoint(int num):

It concatenates the ASCII equivalent of int num at the end of StringBuilder. for example, appendCodePoint(65) will append ‘A’ to the StringBuilder.

StringBuilder insert(int i, String s):

It inserts a string into the StringBuilder at the ith index.

StringBuilder insert(int i, Char c):

It inserts a character into the StringBuilder at the ith index.

StringBuilder insert(int i, Object o):

It inserts the string representation of an Object o into the StringBuilder at the ith index.

StringBuilder reverse():

It is used to reverse the sequence of characters in a StringBuilder object. It returns the reversed StringBuilder object on which it was called. 

StringBuilder delete(int start, int end):

It deletes the substring from the StringBuilder starting from index startup to index end-1.

StringBuilder deleteCharAt(int i):

It deletes a character from the StringBuilder on an ith index.

StringBuilder replace(int start, int end, String str):

It replaces the substring in the StringBuilder (starting from index startup to index end-1) with the String str.

String substring(int i):

It returns a portion of the StringBuilder starting from ith index up to the end, in the form of a String object.

String substring(int start, int end):

It returns a portion of the StringBuilder starting from index startup to the index end-1, in the form of a String object.

IntStream chars():

It returns the integer value of all the characters of the StringBuilder as an Integer stream.

void trimToSize():

It reduces the capacity of the StringBuilder and makes it equal to its length.

String toString():

Returns the String object equivalent to the StringBuilder object, that is, it returns a String representing the StringBuilder object.

CharSequence subsequence(int start, int end):

Returns the character sequence as a subsequence of characters in the StringBuilder.

int offsetByCodePoints(int i, int offset):

Returns the index in the sequence which is offset from index i by Offset code points. It throws IndexOutOfBoundsException when i is negative or larger than the length, or if an offset is positive and the substring starting with index i has fewer than offset code points, or if an offset is negative and the substring before i has fewer than the magnitude of offset code points.

int indexOf(String s):

Returns the first occurring index of String s in the StringBuilder object.

int lastIndexOf(String s):

Returns the last index of the occurrence of String s in the StringBuilder object.

int codePointAt(int i):

Returns a Unicode code point of the character at the ith index.

int codePointBefore(int i):

Returns a Unicode code point of the character before the ith index.

int codePointCount(int start, int end):

Returns the count of the codepoints in the specified sequence range.

#Programs of StringBuilder Class

Let’s see the program to create a StringBuilder object, and append different objects to it.

class Example1
  public static void main(String [] args)
    //creating the StringBuilder objects using different constructors
    StringBuilder str1=new StringBuilder();
    StringBuilder str2=new StringBuilder(60);
    StringBuilder str3=new StringBuilder("Mahesh");

    //checking the length and capacity of StringBuilder objects
    System.out.println("length of str1: "+str1.length()+" and capacity: "+str1.capacity());
    System.out.println("length of str2: "+str2.length()+" and capacity: "+str2.capacity());
    System.out.println("length of str3: "+str3.length()+" and capacity: "+str3.capacity());

    System.out.println("before appending str3: "+str3);

    //Appending String
    String s=" is a good boy and his age is ";

    //Appending integer
    int age=20;

    System.out.println("after appending str3: "+str3);

See the following output.

Programs of StringBuilder Class

Let’s see a Program to fetch the substring from the StringBuilder object, replacing and deleting the substring.

class Example2
  public static void main(String [] args)
    //creating the StringBuilder object
    StringBuilder s=new StringBuilder("home repeat home home");
    System.out.println("original string is: "+s);

    //fetching the substring
    String sub=s.substring(5,11);
    System.out.println("required substring is: "+sub);

    //replace the substring
    String str="sweet";
    System.out.println("required string after replacement is: "+s);

    //finding the last index and deleting the substring
    int startindex=s.lastIndexOf("home");
    int endindex=s.length();
    System.out.println("required string after deletion is: "+s);

See the output.

Constructors of StringBuilder Class

See the following Program to illustrate the use of the reverse method, and check whether a string is a palindrome or not. (palindrome string is the sequence of characters which is the same from both ends).

class Example3
  public static void main(String [] args)
    //creating StringBuilder objects
    StringBuilder str1=new StringBuilder("naman");
    StringBuilder str2=new StringBuilder("ojha");
    StringBuilder str1copy=new StringBuilder("naman");
    StringBuilder str2copy=new StringBuilder("ojha");

    //using reverse function

    //printing original and reverse strings
    System.out.println("original string is: "+str1+"   reverse is: "+str1copy);
    System.out.println("original string is: "+str2+"   reverse is: "+str2copy);

    //converting StringBuilder objects to strings
    String s1=str1.toString();
    String s1c=str1copy.toString();
    String s2=str2.toString();
    String s2c=str2copy.toString();

    //check for palindrome
    //palindrome is a sequence of character which is same from from start and end
    //equals() method compares the content of two strings
      System.out.println(str1+" is palindrome");
      System.out.println(str1+" is not palindrome");

      System.out.println(str2+" is palindrome");
      System.out.println(str2+" is not palindrome");

See the output.

Methods of StringBuilder Class

#Difference between StringBuffer and StringBuilder

Some of the differences between a StringBuffer and StringBuilder are given below:

StringBuffer is synchronized, i.e. thread-safe.StringBuilder is non-synchronized, i.e. not thread-safe.
StringBuffer is less efficient and slower than a StringBuilder as StringBuffer is synchronized.StringBuilder is more efficient and faster than the StringBuffer.
StringBuffer is old, it’s there in the JDK from the very first release.StringBuilder is introduced much later in the release of JDK 1.5


Finally, the StringBuilder Class in Java Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.