Java StringBuilder Class: Methods, Examples and more

Java StringBuilder

Introduction to Java StringBuilder

StringBuilder is a Java Class used to create mutable or successors that can be modified with characters. The StringBuilder class is similar to another class in java, StringBuffer, but is non-synchronized. The StringBuilder class doesn’t provide synchronization, and this is why Java StringBuilder is more suitable to work with than StringBuffer, as it works with a single thread. 

The StringBuilder class provides high performance compared with other string classes, and it is not thread-safe and provides other methods for various purposes. The heap section of the memory allocates memory in the StringBuilder class, and the StringBuilder class is preferred when we manipulate characters in our string. 

In this article, we’ll understand how you can use the StringBuilder class effectively with some examples of this class. 

Syntax

Let us see the syntax of the StringBuilder class below to understand the format of code better to be used in actual Java programming:

public final class StringBuilder
extends Object
implements Serializable, CharSequence

In this syntax, the StringBuilder class extend a public class named ‘Object’ where two interfaces are implemented. You can use Serializable or CharSequence interfaces or any interfaces you want to apply in this class. These interfaces are used to implement various operations on the character of the sequence of our string. 

Important Constructors of StringBuilder class

The StringBuilder class provides several types of constructors used for converting a sequence of characters, the format of characters, and the configuration of some properties of StringBuilder such as size, etc. Here are the essential constructors of the StringBuilder class discussed below:

1. StringBuilder: This constructor is used to create a blank string builder. Initially, the capacity of this builder is set to 16 characters.

2. StringBuilder(int capacity): This constructor also creates an empty builder, but you can specify the builder’s capacity. 

3. StringBuilder(CharSequence): The characters in this builder are created with specified arguments. The CharSequence is used for the sequence of characters in the StringBuilder.

4. StringBuilder(string): This constructor is used to construct a string builder with a given string. 

Check out some of the important questions on StringBuilder in java interview questions.

Methods of StringBuilder class

The StringBuilder class uses various methods. These methods are used to perform different operations on the StringBuilder class. In this section, we will discuss the methods of the StringBuilder class below:

1. append(): This method is used when we need to append a new sequence in the existing sequence of characters in the StringBuilder class. 

Syntax to use append() method:

StringBuilder.append(datatype s)

In the above syntax, s is provided as an argument of specified type – ‘datatype’. The Datatype is String in this case as we are appending string sequence to the existing String.

2. reverse(): As the name suggests, the reverse method is used to reverse the sequence of characters of the StringBuilder string. 

Syntax for reverse() method:

public java.lang.AbstractStringBuilder reverse( )

3. charAt(): This method is useful in the situation when we want a specific character at an index value. We need to give the index value of the character from the string, and it will return that character. 

Syntax for charAt() method:

public char charAt(index_no)

In the above syntax, index_no is used as an argument where we will provide the index of the StringBuilder sequence that will return the character at that index number. 

4. capacity(): To find the initial capacity of the StringBuilder object, the capacity() method is used. However, the default capacity of the StringBuilder class is 16 bytes.  

Syntax to use capacity() method:

public int capacity()

This syntax is used to get the capacity of the StringBuilder sequence. 

5. lastIndexof(): The last index of any particular StringBuilder sequence can be found using this method. 

Syntax of lastIndexof() method:

public int lastIndexof(stringName)

The above syntax takes one parameter as the string’s name and returns the string’s last index. 

6. isEmpty(): This method is used to check whether the StringBuilder object is empty. 

Syntax of isEmpty() method:

public StringBuilder.isEmpty()

It doesn’t require any parameter to be passed and returns True if there is no string and False if a String is present. So, the return type of this method is Boolean. 

7. substring(): substring() method is used to find the substring of the StringBuilder sequence. 

The syntax of the substring() method is as follows:

public StringBuilder.substring(index_start, index_end+1)

The above syntax requires two parameters as the starting and ending index of the sequence of StringBuilder. It returns the string of characters for the sequence according to the index number provided in the method. 

8. length(): This method is used to find the length of the sequence of StringBuilder. The syntax to use the length() method is as follows:

public StringBuilder.length()

The above syntax doesn’t need any parameter, and it returns the length of the StringBuilder sequence. 

9. indexof(): This method is used when we need to find the first index of a given string in the StringBuilder sequence. In the absence of a string, it returns -1.

Syntax to use indexof() method:

public int indexof(StringName)

The above syntax takes one parameter as the name of the string and returns the first index value of the string and -1 if the string is not present. 

10. delete(): When we don’t need a particular sequence from the StringBuilder sequence, we will use the delete() method. 

Syntax to use delete() method:

public StringBuilder.delete(index_start, index_end+1)

The above syntax requires two parameters as index numbers and returns the StringBuilder reference. 

Examples of StringBuilder: Let us see some examples better to understand the methods of the StringBuilder class in Java:

StringBuilder append() method

Example:

public class AppendExample{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“Learn”);
mystring.append(“ Java StringBuilder”);
System.out.println(mystring);
mystring.append(“ from GLA”);
System.out.println(mystring);
}
}

Output:

Learn Java StringBuilder

Learn Java StringBuilder from GLA

In the above program, the String ‘mystring’ is appended with a substring. So the main string and substring are joined as an output. 

StringBuilder insert() method

Example:

public class InsertMethodEg{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“Learn”);
mystring.insert(2, “String”);
System.out.println(mystring);
}
}

Output:

LeStringarn

In the above code, we first declared a string with the name ‘mystring’ and then inserted another substring at the specified index of the main string. 

StringBuilder replace() method

Example:

public class ReplaceMethodEg{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“GreatLearning”);
mystring.replace(10,14,”StringBuilder”);
System.out.println(mystring);
}
}

Output:

GreatLearnStringBuilder

The above program replaces the substring specified with index numbers from the main string with another substring. This way, you can replace the characters or the whole string using the index number of the main string. 

StringBuilder delete() method

Example:

public class DeleteMethodEg{
public static void main (String args[]){
StringBuilder mystring = new StringBuilder(“GreatLearning”);
mystring.delete(0,5);
System.out.println(mystring);
}
}

Output:

Learning

The above code is used to delete a sequence of characters from the string based on the specified indexes. In this example, we specified the index number from 0 to 5, which will remove the string characters on the index 0 to 4 only and return the remaining string. 

StringBuilder reverse() method

Example:

public class ReverseMethodEg{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“GreatLearning”);
mystring.reverse();
System.out.println(mystring);
}
}

Output:

gninraeLtaerG

The reverse method is used to reverse the main string. Here in our example, we created a string with the value ‘GreatLearning’ in which the reverse function is used that reverses the string in our output. 

StringBuilder capacity() method

Example:

public class CapacityMethodEg{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder();
mystring.append(“Great Learning”);
System.out.println(mystring);
System.out.println(“The capacity of mystring is: ”+ mystring.capacity());
}
}

Output:

Great Learning

The capacity of mystring is: 16

In the above code, we used the capacity() method of our StringBuilder class that will return the current capacity of the string. The default capacity for any string is 16 bytes which increases when the number of characters increases more than 16 with the formula n*2+2. 

StringBuilder ensureCapacity() method

Example:

public class AnotherCapacityEg{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder();
mystring.append(“Great learning”);
System.out.println(“The capacity of the string is: “ + mystring.capacity());
mystring.append(“Academy”);
System.out.println(“The capacity of the string is: ” + mystring.capacity());
mystring.ensureCapacity(15);
System.out.println(“Now the capacity of the string is same as: “ + mystring.capacity());
mystring.ensureCapacity(44);
System.out.println(“The capacity of the string is now: ” + mystring.capacity());
}
}

Output:

The capacity of the string is: 16

The capacity of the string is: 34

Now the capacity of the string is the same as: 34

The capacity of the string is now: 70

In this example, the ensureCapacity() method is used to ensure that the capacity of the string is minimum before we perform more operations on that string. It is essential to know the capacity of the string before performing any operation. 

Conclusion

This is all about the Java StringBuilder class, where we have seen the methods that can be used in this class. We have looked at examples of some of these methods. The Java StringBuilder class has various methods to be used in Java, which are helpful for different scenarios. However, the methods apply to the Strings of characters.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top