What is StringBuilder in Java? Methods and Examples
Updated on 18th Dec, 23 9.1K Views

In this blog, we will learn all about the StringBuilder class of Java. We will see the different constructors used in the StringBuilder class, along with the in-built methods provided in this class. Also, you will learn to implement the methods with the help of examples. Apart from this, the difference between StringBuilder and StringBuffer classes will also be discussed.  

Table of Contents

To improve your Java skills and start coding like a pro, watch our YouTube video!

Java Course | Java Tutorial for Beginners | Java Training | Intellipaat

What is StringBuilder in Java?

StringBuilder was introduced by JDK 5 as an alternative to the String class in Java. The StringBuilder class is used to build mutable strings, i.e., strings that can be modified. This means that we can make changes to the same string object without creating a new object with every update. This class is a part of the Java.lang package

To declare a StringBuilder class in a Java program, the following syntax is followed:

public final class StringBuilder

    extends Object

    implements Serializable, CharSequence

Are you ready to advance your Java knowledge? Enroll in our thorough Java Course today to maximize your potential!

Constructors in Java StringBuilder class

The following list contains the names of constructors in the StringBuilder class along with their functions:

1. StringBuilder(): This constructor creates a string builder that does not contain any characters but can hold 16 characters initially.

2. StringBuilder(int length): This constructor also creates a string builder that does not hold any characters, but the length argument specifies the initial capacity.

3. StringBuilder(CharSequence seq): It constructs a string builder containing the sequence of characters as specified by CharSequence.

4. StringBuilder(String str): It creates a string builder with the specified string. In other words, it initializes the StringBuilder object with the specified string.

Example:

class Person:
    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Creating an instance of the Person class using the constructor
person1 = Person("Alice", 30)

# Accessing the attributes of the object
print(f"Person's name: {person1.name}")
print(f"Person's age: {person1.age}")


Here, the __init__ method serves as the constructor for the Person class. It takes name and age as two parameters and initializes the attributes of the object (self.name and self.age). When you create an instance of the Person class using the constructor, you pass values for name and age, and the object is initialized with those values.

Want to ace your next Java interview? Check out our recent blog post about the most common Java Interview Questions and Answers!

In-Built Methods of StringBuilder Class

There are several built-in methods provided by the StringBuilder class. Every method has its distinct functionality. These methods are explained in detail below:

1. StringBuilder append(String x ): This method is used to append the existing string with the mentioned string. This means it concatenates the mentioned string and the existing string. This can also take arguments like boolean, char, int, double, and float.  

2. StringBuilder insert(int offset, String x): This method can be used when we want to insert the mentioned string at a particular offset position in the existing string. This method can also take arguments such as boolean, char, int, double, float, etc.

3. StringBuilder replace(int start, int end, String x): It is used for replacing the original string with the specified string between the mentioned start index and the end index. 

4. StringBuilder delete(int start, int end): This method will delete the portion of the string lying between the mentioned start index and end index.

5. StringBuilder reverse(): This method is used for reversing the string

6. int capacity(): The capacity() method is used to return the current capacity of the StringBuilder object, where capacity refers to the amount of storage available to insert new characters in the string.

7. void ensureCapacity(int min_capacity): This method is used to ensure that the capacity is equal to the specified minimum capacity.

8. char charAt(int index): This method returns the character present at the specified index value.

9. int length(): It returns the total number of characters present in the string. 

10. String substring(int startIndex): This method will return the substring from the mentioned starting index.

11. int indexOf(String x): This returns the index value where the first instance of the specified string is encountered.

12. Void trimToSize(): This method is used for trimming the capacity of the string object of the StringBuilder class.

How to Use the StringBuilder Class and Its Methods

In this section, we will understand how the above-mentioned methods are practically used in Java. 

Example 1. StringBuilder append(String x)

An example of a Java program implementing this method is given below.

// Java program to illustrate the
// StringBuilder append(boolean a)

import java.lang.*; 
public class Test {
    public static void main(String[] args) {
        
// Creating a StringBuilder object
        StringBuilder sb = new StringBuilder("Hello");
        
// Appending more text to the StringBuilder
        sb.append(", welcome to ");
        sb.append("Intellipaat!");
      
// Displaying the final string
        System.out.println("Final String: " + sb.toString());
    }
}

The final output will look as follows:

Final String: Hello, welcome to Intellipaat!

Example 2. StringBuilder insert(int offset, String x)

An example demonstrating the usage of this method is given below:

import java.lang.*;
public class Test {
   public static void main(String[] args) {
      StringBuilder obj = new StringBuilder("Intelipaat \n");
      System.out.println("Before Insertion = " + obj);
      // insert character value at offset 4
      obj.insert(4, 'l');
      // prints StringBuilder after insertion
      System.out.print("After insertion = ");
      System.out.println(obj.toString());
   }    
}  

The output of this program is as follows:

Before Insertion = Intelipaat 

After insertion = Intellipaat 

Example 3. StringBuilder replace(int start, int end, String x)

The following example shows how to use the replace() method:

import java.lang.*;
public class Test {  
    public static void main(String[] args) {  
        StringBuilder obj = new StringBuilder("Welcome in Intellipaat.");  
        System.out.println("string: "+obj);  
        System.out.println("after replacing: "+obj.replace(8, 10, "to"));  
    }  
}  

We get the following output from this:

string: Welcome in Intellipaat.

after replacing: Welcome to Intellipaat.

Example 4. StringBuilder delete(int start, int end)

The following example shows how to use the delete() method of the StringBuilder class:

import java.lang.*;
// Java program to demonstrate
// the delete() Method.
class Test{
public static void main(String[] args)
{
 // create a StringBuilder object
 // with a String pass as parameter
 StringBuilder obj = new StringBuilder("WelcomeIntellipaat \n");
 // print string
 System.out.println("String before removal = "   + obj.toString());
 // remove the substring from index 0 to 7
 StringBuilder afterRemoval = obj.delete(0, 7);
 // print string after removal of substring
 System.out.println("String after removal= "   + afterRemoval.toString());
}
}

The following output is received:

String before removal = WelcomeIntellipaat 

String after removal= Intellipaat 

Example 5. StringBuilder reverse()

The example given below demonstrates how the reverse() method works:

import java.lang.*;
class Test {
public static void main(String[] args)
{
 StringBuilder obj = new StringBuilder("Intellipaat");
 // print string
 System.out.println("String = "   + obj.toString());
 // reverse the string
 StringBuilder reverseStr = obj.reverse();
 // print string
 System.out.println("Reverse of the String = "   + reverseStr.toString());
}
}

The output that we get is as follows:

String = Intellipaat

Reverse of the String = taapilletnI

Example 6. int capacity()

The example given below demonstrates how the capacity() method works in the Java StringBuilder class:

import java.lang.*;
class Test {
public static void main(String[] args)
{
 // create a StringBuilder object,
 // default capacity will be 16
 StringBuilder obj = new StringBuilder();
 // get default capacity
 int capacity = obj.capacity();
 System.out.println("Default Capacity of the StringBuilder = "   + capacity);
 // add the String to StringBuilder Object
 obj.append("Intellipaat");
 capacity = obj.capacity();
 System.out.println("StringBuilder = " + obj);
 System.out.println("Current Capacity of StringBuilder = "   + capacity);
}
}

The output of this program is as follows:

Default Capacity of the StringBuilder = 16

StringBuilder = Intellipaat

Current Capacity of StringBuilder = 16

Example 7. void ensureCapacity(int min_capacity)

The following example shows the implementation of the ensureCapacity() method in Java:

import java.lang.*;
class Test { 
public static void main(String[] args) 
{ 
 // create a StringBuilder object 
 StringBuilder obj = new StringBuilder(); 
 // print string capacity 
 System.out.println("capacity before using ensureCapacity "   + "method = "   + obj.capacity()); 
 // apply ensureCapacity() 
 obj.ensureCapacity(18); 
 // print string capacity 
 System.out.println("capacity after using ensureCapacity"   + " method  = "   + obj.capacity()); 
} 
} 

The output we get is as follows:

capacity before using ensureCapacity method = 16

capacity after using ensureCapacity method  = 34

Example 8. char charAt(int index)

The following example shows the implementation of the charAt() method in Java:

class Test{ 
public static void main(String[] args) 
{ 
 // create a StringBuilder object 
 StringBuilder obj = new StringBuilder(); 
 // add the String to StringBuilder Object 
 obj.append("Intellipaat"); 
 // get char at position 1 
 char c = obj.charAt(1); 
 // print the result 
 System.out.println("StringBuilder Object"   + " contains = " + obj); 
 System.out.println("Character at Position 1"   + " in StringBuilder = " + c); 
} 
} 

The output received is as follows:

StringBuilder Object contains = Intellipaat

Character at Position 1 in StringBuilder = n

Check out this Java Tutorial tutorial on Java to learn the basics of Java.

Example 9. int length()

See the example given below to understand how the length() method works in Java.

// Java program to demonstrate 
// the length() Method. 
class Test { 
public static void main(String[] args) 
{ 
 // create a StringBuilder object 
 // with a String pass as parameter 
 StringBuilder  obj  = new StringBuilder("Intellipaat \n"); 
 // print string 
 System.out.println("String = "   + obj.toString()); 
 // get length of StringBuilder object 
 int length = obj.length(); 
 // print length 
 System.out.println("length of String = "   + length); 
} 
} 

This program gives the following output:

String = Intellipaat

length of String = 13

Example 10. String substring(int startIndex)

The following example shows the implementation of the charAt() method in Java:

// Java program to demonstrate 
// the charAt() Method. 
class Test{ 
public static void main(String args[]){  
String obj="Intellipaat";  
System.out.println(obj.substring(0,5));
System.out.println(obj.substring(6)); 
}
}  

Output:

Intel

ipaat

Example 11. int indexOf(String x)

The following Java code demonstrates the working of the indexOf() method.

import java.lang.*;
public class Index1 {
public static void main(String args[])
{
 // Initialising String
 String obj = new String("Welcome to Intellipaat");
 System.out.print("First encountered I at position : ");
System.out.println(obj.indexOf('I'));
}
}

This program gives the following result:

First encountered I at position: 11

Example 12. Void trimToSize()

The working of the trimToSize() method is shown in the example below:

import java.lang.*;
public class Test{
  public static void main(String[] args) {
    StringBuilder obj = new StringBuilder();
    System.out.println("Default Capacity: "+obj.capacity());
    //append string
    obj.append("Intellipaat");
    System.out.println("String appended: "+obj);
    //cleanup buffer
    obj.trimToSize();
    System.out.println("Capacity after using trim: "+obj.capacity());
  }
}

We get the following result:

Default Capacity: 16

String appended: Intellipaat

Capacity after using trim: 11

StringBuilder Vs. StringBuffer Class

Both the StringBuilder and StringBuffer classes can create mutable string objects and store them in heap memory. Although StringBuilder and StringBuffer classes are similar, their functioning is quite different. The major difference between them is the synchronization of threads. The following table explains and highlights the differences between the StringBuilder and StringBuffer classes.

StringBuilderStringBuffer 
StringBuilder class methods are not synchronized, which means it is not thread-safe.StringBuffer class is synchronized, i.e., it is thread-safe.
More than one thread can simultaneously call the methods of this class.Only one thread can call its method at one time.
StringBuilder is faster and more efficient.The StringBuffer class is slower and less efficient because of the synchronization property.
This class was introduced in Java 1.5 to overcome the limitations of the StringBuffer class.This was introduced in Java 1.0.

If you’re wondering which of these is better, it depends on the different requirements. If you utilize a single-threaded environment or are not concerned about thread safety, you should go for the StringBuilder class. Otherwise, use the StringBuffer class to ensure that the operations are thread-safe.

Conclusion

When high performance is needed, particularly in loops or activities that involve string alterations, it is more efficient to use StringBuilder instead of implementing immutable strings. The mutable aspect of StringBuilder is very useful for algorithms such as parsing, reversing, or altering characters for handling strings. StringBuilder allows for in-place modifications, reducing memory overhead and enhancing overall performance. 

Join our Intellipaat community today and interact with other developers all over the world! Join now and push your Java abilities to new heights!

Course Schedule

Name Date Details
Python Course 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 09 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 16 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

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

Speak to our course Advisor Now !

Associated Courses

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.