Free Courses

StringBuilder Class in Java with Examples

Learn about StringBuilder in Java.

Updated - 20 Jun 202216 mins readPublished : 7 Jan 2022
Published : 7 Jan 2022
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

The StringBuilder class is used for storing the mutable (changeable) sequence which means we can update the elements of the StringBuilder class without creating a new StringBuilder sequence in memory.

Scope of Article

  • This article defines the StringBuilder class and explains various properties of the StringBuilder class.
  • This article discusses the internal working of the StringBuilder class and shows the implementation of the methods of the StringBuilder class with proper examples.

Introduction

StringBuilder has high performance as compared to other String classes because it is not thread-safe and also provides various types of additional methods such as deleting the elements, updating the elements, etc. The memory allocation of the StringBuilder class is done in the heap section of the memory.

What is StringBuilder in java

Let’s suppose you have a word “scaler” that is present in a particular memory location and it is stored in the String class. When you add any extra character in the word, a new memory is allocated for every updation, this causes memory wastage in the case when we store the word in the String class but when we store the sequence in the StringBuilder class no new memory is allocated in this case during adding of the new characters in the case of StringBuilder class. This property of the StringBuilder class is called “mutable” which means updating is done in the sequence itself.

So we prefer the StringBuilder class over the String class when we have to perform characters manipulation in our string. Let's dive deep and understand various characteristics of the StringBuilder class.

Syntax of StringBuilder Class

StringBuilder class extends the Object class that is the parent class of all the predefined class and user-defined class in java that contains methods like hashCode(), equals() method and implementing the two interfaces Serializable and CharSequence that helps for implementing various types of different operations of the character of sequence.

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence

syntax of stringbuilder class

How StringBuilder Works Internally

StringBuilder class uses a Buffer(array) that can be altered (means updating allows when new characters are added or inserted in between the existing characters that are present in StringBuffer already).

Now think about what will happen when the Buffer gets full ?. When the Buffer gets full automatically a new Buffer is created which is double the size of the older buffer and no new memory is not allocated for every updation also StringBuilder is not synchronised that means multiple threads can access the StringBuilder object at the same time that's why StringBuilder is not a thread safe class.

Let's discuss some various some internal contructors of the StringBuilder class.

Constructor in Java StringBuilder Class

StringBuilder class provides different types of the constructors that help for converting the oridinary Sequence, characters to StringBuilder format and helps to configure some properties of StringBuilder size as size, etc. Let's discuss different Constructors one by one.

1. StringBuilder():

This constructor is used for creating a StringBuilder with no characters and the initial capacity is 16 bytes. The maximum elements that StringBuilder can store is known as the capacity of the StringBuilder. We will discuss some more about the capacity later in this article.

Syntax:

StringBuilder ob = new StringBuilder();

2. StringBuilder(int capacity):

This constructor is used for initializing the capacity of the StringBuilder that contains no characters. Below Syntax of the constructor is initializing the size of empty StringBuilder of 10 bytes.

Syntax:

StringBuilder ob=new StringBuilder(10);

3. StringBuilder(char sequence):

This constructor is used for creating a StringBuilder of charsequence.The charsequence is the sequence of the characters.

Syntax:

StringBuilder ob=new StringBuilder(CharSequence);

4. StringBuilder(String):

This constructor is used for creating the StringBuilder of a given String.

Syntax:

StringBuilder ob=new StringBuffer(String);

Let's understand these constructors with the help of an example.

        StringBuilder first=new StringBuilder("Scaler");
        //Printing the Scaler in StringBuilder form
        System.out.println(first);
        StringBuilder second=new StringBuilder(10);
        //Printing the capacity of the StringBuilder
        System.out.println(second.capacity());

In the first constructor we simply pass the String and after then print the given String in the StringBuilder form and In the second constructor we are creating an empty StringBuilder of capacity 10 bytes.

Methods of StringBuilder Class

StringBuilder class provides various types of inbuilt methods that help in performing a different kinds of operations on StringBuilder. Let's discuss each method one by one.

1. append() method:

This method is used for appending the new sequence in the exisiting sequence of the StringBuilder class.

Syntax:

StringBuilder.append(datatype) append(datatype) method of the StringBuilder class is used for appending the element of a particular datatype at the end of the current sequence of the StringBuilder also there is no error occur if we append the values in the empty StringBuilder sequence.

Parameter: This method takes one parameter that is any datatype value that needs to be appended in the StringBuilder sequence.

ReturnType: This method returns the reference of StringBuilder object

        StringBuilder first=new StringBuilder("String");
        //This line is appending the String in the sequence
        first.append("hello");
        System.out.println(first);
        //This line is appending the integer to the sequence
        first.append(1);
        System.out.println(first);

In the above program, we are appending a different kinds of datatype values to the sequence of StringBuilder. In the above case, we are appending the int and String datatypes values to the StringBuilder sequence.

Output:

Stringhello
Stringhello1
  • appendCodePoint() method is used for appending the String representation of the unicode characters to the sequence of the StringBuilder. For example the unicode value of character 'A' is 67. This unicode value is converted to the String "A" and then append to the sequence of the StringBuilder class.

Syntax:

StringBuilder appendCodePoint(int value): This method takes the Unicode value and adds the String representation of the Unicode at the end of the sequence of StringBuilder.

Parameter: This method takes one value, the Unicode value as a parameter.

Return type: This method returns the object reference of the StringBuilder class.

Let' understand this method using an example.

 StringBuilder m=new StringBuilder("Scaler");
  //Appending the character "a" (97) to the sequence.
    m.appendCodePoint(97);
    System.out.println(m);

Output:

Scalera

In the above snippet, we are adding the Unicode value of 'a' to the StringBuilder sequence and the resultant sequence is Scalera.

2. capacity() method:

This method is used for finding the intial capacity of the StringBuilder object. The default capacity of StringBuilder class is 16 bytes.

Syntax:

int capacity(): This method returns the capacity of the StringBuilder object. The default capacity of the StringBuilder is 16 bytes. When the capacity of StringBuilder gets full the new capacity of StringBuilder will be (previouscapacity+1)X2.

Return type: This method returns the current capacity in int format.

Let's understand this method using an example.

    StringBuilder m=new StringBuilder();
    System.out.println("Default Capacity"+m.capacity());
    //Capacity increase by (16(default capacity)+1)*2=34
    m.append("12345678912345678");
    System.out.println("new Capacity"+m.capacity());


Output:

Default Capacity 16
new Capacity 34

In the above snippet, the capacity of the StringBuilder sequence increases when the capacity gets full. Default capacity is 16 and the new capacity is (16+1)*2 i.e 34.

3. charAt() method:

  • char charAt(index): This method is used for getting character value present at the index of the StringBuilder sequence.

Parameter: This method takes one parameter the index of the character. The range of index must be in the range [0, SizeofStringBuilder-1]. if the value of the index outside the range this cause an indexoutofException and program will be stopped.

Return type: This method returns the character present at the index value in the StringBuilder sequence.

Let's understand this method using an example.

 StringBuilder m=new StringBuilder("Scaler");
 //Printing the character present at index 0
    System.out.println(m.charAt(0));
//This line will cause an error due to the invalid
//Range of the index value
    System.out.println(m.charAt(11));

Output:

S
Exception in  thread "main" java.lang.StringIndexOutOfBoundsException Create breakpoint : Index 11, length 6

The above snippet is printing the character that is present at index 0 and the second printing line is causing an error due to the invalid range of index value.

  • deleteCharAt() method: This method is used for deleting the particular character at the given index from the StringBuilder sequence.

Syntax:

  • StringBuilder.deleteCharAt(index): This method is used for delete a particular character present at the index in the StringBuilder sequence.

Parameter: This method takes one parameter i.e the index of the character.

Return type: This return type of this method is StringBuilder reference.

Let's understand this method using an example.

 StringBuilder m=new StringBuilder("Scaler");
 //Deleting the character at index 2.
    m.deleteCharAt(2);
    System.out.println(m);

Output:

Scaler

The above snippet is used for deleting the character at index 2 of StringBuilder Scaler.

  • setCharAt() method: This method is used for inserting the character at the particular index of the StringBuilder sequence.

Syntax:

  • void setCharAt(index, char c): This method is used for inserting the character at the particular index in the StringBuilder sequence. The range of index should be in [0-lengthofsequence].

Parameter: This method takes two parameters one is the index value and the second parameter is the character that to is inserted at the index position in the StringBuilder sequence. if the value of the index outside the range this cause an indexoutofException and program will be stopped.

Return type: The return type of this method is void.

Example:

StringBuilder m=new StringBuilder("Scaler");
//Inserting the character at index 0
    m.setCharAt(0,'D');
//Inserting the character at index 2
    m.setCharAt(2,'E');
//Printing the sequence    
    System.out.println(m);
//This line will cause an error due to invalid range.    
    m.setCharAt(102,'E');

Output:

DcEler
Exception in thread "main" java.lang.StringIndexOutOfBoundsException Creare breakpoint : index 102, length 6

The first printing line will print the updated sequence of the StringBuilder, but the second printing line will cause an error due the invalid range of the index in the parameter of the method.

4. reverse() method:

This method is used for reversing the StringBuilder sequence.

Syntax:

StringBuilder.reverse(): This method is used for reverse the StringBuilder sequence.

Parameter: This method doesn't take any parameters.

Return type: This method return StringBuilder reference.

Example:

    StringBuilder m=new StringBuilder("Scaler");
    //Reverse the StringBuilder sequence
    m.reverse();
    System.out.println(m);

Output:

relacS

The above snippet reverse the StringBuilder sequence i.e Scaler to relcaS.

5. length() method:

This method is used for finding the length of the StringBuilder sequence. Length is the number of elements of the StringBuilder sequence.

Syntax:

StringBuilder.length(): This method is used for calculating the length of the StringBuilder sequence.

Parameter: This method doesn't take any parameters.

Return type: This method returns the length of the StringBuilder sequence.

Example:

StringBuilder m=new StringBuilder("Scaler");
    System.out.println(m.length());

Output:

6

The above snippet is printing the length of the StringBuilder sequence i.e 6 is the length of the sequence in the above snippet.

6. indexof() method:

This method is used for finding the first index of the given String in the sequence of the StringBuilder.If the String is not present in the sequence of the StringBuilder this method will return -1.

Syntax:

  • int indexof(String): This method returns the first index of the given String in the sequence if it is present, Otherwise this method returns -1 that indicates String is not present in the StringBuilder sequence.

Parameter: This method takes one parameter i.e String.

Return type: This method returns the first index value of String if present, otherwise returns -1.

Example:

    StringBuilder m=new StringBuilder("Scaler");
    //Printing the first index of "S" String 
    System.out.println(m.indexOf("S"));
    //This line will return -1 because sequence doesn't
    //contains "z" as a String.
    System.out.println(m.indexOf("z"));

Output:

0
-1

In the above snippet, the "S" String occurs at the first index of the StringBuilder sequence that's why we get 0 in the first printing statement, but in the second printing line, we get -1 because "z" String is not present in the sequence of StringBuilder.

7. lastIndexof() method:

This method is used for finding the last index of the particular sequence in the StringBuilder sequence. If the sequence is not present in the StringBuilder sequence. This method returns -1, otherwise will return the starting index value of the sequence.

Syntax:

int lastIndexof(String): This method returns the last index of the given String in the sequence of the StringBuilder.

Parameter: This method takes one parameter i.e String.

Return type: This method returns the last index of the String, if it is present in the Sequence of StringBuilder, Otherwise returns -1.

Example:

    StringBuilder m=new StringBuilder("ScalerScaler");
    //This line will returns 6 
    System.out.println(m.lastIndexOf("Scaler"));
    //This line will returns -1
    System.out.println(m.lastIndexOf("z"));

Output:

6
-1

In the above snippet, the first printing line will return the last index of String i.e Scaler that is present at index 6, So 6 is returns but in the second printing line "z" String is not present in the sequence of the StringBuilder that's why -1 is prints.

8. isEmpty() method:

This method is used to check whether the StringBuilder object contains any sequence or not.

Syntax:

StringBuilder.isEmpty(): If the StringBuilder sequence is empty this method will return true otherwise returns false. When the StringBuilder sequence is not empty.

Parameter: This method doesn't take any parameters.

Return type: The return type of this method is boolean i.e either true or false.

Let's understand this method using an example.

StringBuilder ob=new StringBuilder("");
   System.out.println(ob.isEmpty());
   ob.append("Aayush");
   System.out.println(ob.isEmpty());

Output:

true
false

The true value is returned because at the starting the StringBuilder is empty but appending the text to the StringBuilder contains some sequence that why false is returned.

9. substring() method:

This method is used for getting the substring from the StringBuilder sequence.

Syntax:

StringBuilder.substring(start index,endingindex+1): This method takes two parameters to start index of the sequence and the ending index of the sequence. The starting index must be greater than 0 and smaller and equal to the ending index.

Parameter: This method takes two parameters i.e Starting index and the ending index of the sequence.

Return type: The return type of this method is String.

Let's understand this method using an example.

  StringBuilder m=new StringBuilder("Aayush");
  
        System.out.println(m.substring(4));
        //This line will cause an error due to 
        //invalid value of indexes
       // System.out.println(m.substring(-1,5));
        System.out.println(m.substring(2,5));
    

Output:

sh
yus

The string "sh" is returned because we want substring starting from index 4 and "yus" is returned because the index of y is 2 and the ending index is 4 that's why we get substring "yus".

10. delete() method:

This method is used for deleting the particular sequence from the StringBuilder.

  • Syntax:

StringBuilder.delete(startindex,endingindex+1) method takes two arguments startingindex and the endingindex of the sequence that we want to delete from the StringBuilder sequence.

Parameter: This method takes two parameters the starting index must be greater than equal to 0 and smaller than equal to the ending index.

Return type: This method returns the StringBuilder reference.

 StringBuilder m=new StringBuilder("Aayush");

        System.out.println(m.delete(4,7));
        //This line will cause an error due to
        //invalid value of indexes
       // System.out.println(m.substring(-1,5));
        System.out.println(m.delete(2,5));

Output:

Aayu
Aa

The seqeunce Aayu is returned because we have deleted the sequence starting from index 4 i.e sh and in the next deletion we delete the sequence starting from index 2 and ending index 5(empty sequence) that's why Aa is returned.

These are some methods of the StringBuilder class.

Calling StringBuilder Methods

We can call StringBuilder class methods using the object of the StringBuilder class.Because StringBuilder class is not a primitive class that's means we have to create a StringBuilder object for accessing its methods.

Let's understand how to call StringBuilder methods using an example.

 StringBuilder ob=new StringBuilder("Aayush");
 //Calling the StringBuilder method using the object of 
 //the StringBuilder class
   ob.append("Scaler");
   System.out.println(ob);
   

Output:

AayushScaler

In the above snippet, we are appending the "Scaler" text in the StringBuilder sequence.

StringBuilder Length and Capacity.

StringBuilder.length() and StringBuilder.capacity() are the two methods of the StringBuilder class are somewhat make sense similar but they are totally different.

StringBuilder.Capacity() This method indicates the maximum number of elements the StringBuilder object can hold. When the StringBuilder capacity gets full.

Internally StringBuilder updates the capacity by (previouscapcity+1)*2. By default 16 bytes is the capacity of the StringBuilder when StringBuilder contains no elements.

java stringbuilder capacity

In the above image, the capacity of the StringBuilder is 16 bytes but the current sequence length is 9 bytes.

StringBuilder.length(): The method tells us the length of the current StringBuilder sequence that means the number of characters of the StringBuilder sequence. The length of the StringBuilder is always smaller and equal to the capacity of the StringBuilder capacity. In the above picture, the number of characters of StringBuilder sequence is 9 that's why the length is 8.

Performing StringBuilder Operations

  • Iterating StringBuilder characters: Using the for loop is one of the best ways for iterating the characters of the StringBuilder.

Let's understand this using an example.

Example:

         StringBuilder m=new StringBuilder();
         //Appending the String to the StringBuilder object
         m.append("Scaler");
         System.out.println("Characters");
         for(int i=0;i<m.length();++i){
         //Use charAt() method for iterating the 
         //Characters
             System.out.println(m.charAt(i));
         }

Output:

Characters

S
c
a
l
e
r

In the above snippet we are iterating on the characters of the StringBuilder sequence with the help of the String.charAt(index) method and for a loop.

  • Adding text to a StringBuilder object: The append() method of the StringBuilder class is used for appending the text in the current sequence of StringBuilder.

Let's understand how to add text to a StringBuilder object using an example.

         StringBuilder m=new StringBuilder();
         System.out.print("Old value: ");
         //Appending the text in the empty StringBuilder
         m.append("This");
         System.out.println(m);
         System.out.print("New value: ");
         //Appending the text in the current sequence of 
         //StringBuilder
         m.append("Scaler");
         System.out.println(m);

Output:

Old value: This
New value: ThisScaler
  • Modifying the text in the StringBuilder object: We can modify the existing StringBuilder sequence in two ways either deleting the some elements of the sequence or inserting the text in the StringBuilder sequence. For inserting the text at the particular index, we will use StringBuilder.insert(index,text) method of the StringBuilder class.

Example:

        StringBuilder m=new StringBuilder();
        m.append("Scaler");
        System.out.println(m);
        //Inserting the text at the 2nd index of
        //StringBuilder sequence
        m.insert(2,"Hello");
        System.out.println(m);

Output:

Scaler
ScHelloaler

The above snippet is inserting the text at the 2nd index of the existing sequence of the StringBuilder.

  • Deleting the text from StringBuilder object: We can delete the text from the StringBuilder sequence using StringBuilder.delete(startindex,endindex+1) method. Let's understand how to delete the text from the StringBuilder sequence using an example.
   StringBuilder ob=new StringBuilder("ScalerHelloWorld");
   //Printing the StringBuilder sequence
        System.out.println(ob);
//Deleting the text start from 6th index and ends 10th index
        ob.delete(6,11);
        System.out.println(ob);

Output:

ScalerHelloWorld
ScalerWorld

In the above snippet, we delete the Hello from the StringBuilder sequence that is present at the starting index 6 and ends at the 10th index.

Searching The Text in a StringBuilder Object

If we want to search particular text in the StringBuilder object. We can use StringBuilder.indexOf(text) method. This method returns the first index of the text if it is present in the StringBuilder sequence, otherwise returns -1.

Let's understand how to search the text in the StringBuilder object using an example.

     StringBuilder ob=new StringBuilder("ScalerHelloWorld");
     //Searching the text "World" in the sequence
        System.out.println(ob.indexOf("World"));
     //Searching the text "ScalerZ" in the StringBuilder 
     //Sequence
        System.out.println(ob.indexOf("ScalerZ"));

Output:

11
-1

The world is present in the StringBuilder sequence at the starting index 11 but the text "ScalerZ" is not present in the StringBuilder sequence that's why -1 will return.

Converting The StringBuilder Object to a String

Suppose you want to change the StringBuilder object to String because next operations need String an input instead of StringBuilder in a particular program. What should you do? StringBuilder class provides a method StringBuilder.toString() that converts the StringBuilder object to the String object.

Let's understand StringBuilder.toString() method using an example.

        StringBuilder m=new StringBuilder();
        m.append("Scaler");
        //Converting StringBuilder object to String.
        String st=m.toString();
        System.out.println(st);

Conclusion:

  • StringBuilder class is used for storing mutable elements.
  • StringBuilder is non-synchronous multiple threads can access StringBuilder object at the same time.
  • StringBuilder is fastest among all the other String classes such as String and StringBuffer .
  • The default capacity of the StringBuilder is 16 bytes.

FAQ's:

  1. What is the use of String builder?

    StringBuilder class is used for storing the mutable elements that save lots of memory because no extra memory is used after updation on the StringBuilder sequence.

  2. Why do we use String builder in Java?

    Because it is not thread-safe multiple threads can access the StringBuilder object that increases the performance of StringBuilder because no thread has to wait for their turn for a particular operation.

  3. Is String builder efficient?:

    Yes, StringBuilder is efficient because due to the mutable and non-thread-safe property of the StringBuilder.

  4. Which is better: StringBuilder or String?:

    StringBuilder is better because it is 6000 times faster than the String class.

Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
certificate icon
Certificates
Java Tutorial
This program includes modules that cover the basics to advance constructs of Java Tutorial. The highly interactive and curated modules are designed to help you become a master of this language.'
If you’re a learning enthusiast, this is for you.
Module Certificate
Criteria
Upon successful completion of all the modules in the hub, you will be eligible for a certificate.
You need to sign in, in the beginning, to track your progress and get your certificate.
Free Courses by top Scaler instructors