StringBuilder Class in Java

StringBuilder Class in Java

We have studied many things about the concept of String. We have also seen that the strings are immutable and studied why are they immutable. Sometimes, using string is great, since it does not allow us to make changes to the object once it is created. But what if we need to update the contents of the string object that we have created?

Well, we know that if we try to make any changes, with those changes, another object will be created. But if we are doing this repeatedly, it will create separate objects every time we make some change. The fact is that it takes some time to create a new string object, and if we are doing this a lot of times, it is going to be a quite time-consuming task.

What if we could edit the contents of the same objects? It would be handy when we want to frequently edit the content of some string. As an example, let’s just consider that we have created a String object with a string literal ”Gyani”, and then, we are concatenating another string ”Pandit”, let’s write a program for the same.

public class Concatenation {
public static void main(String[] args) {
String str1 = new String(“Gyani”);
String str2 = new String(“Pandit”);
str1 = str1+str2; // concatenating two strings. reference variable is str1.
System.out.println(str1);
}
}

So, as you can see that we had two different string objects, and we concatenated them to create a new string object(even if it is being referenced by one of the existing reference variables).

Internally, we had to create a new object with the literal ”GyaniPandit”, since we cannot modify the content of the existing string object.

How to create a StringBuilder object

There is another class, called StringBuilder, which can help us in this situation. With StringBuilder, the character sequence is mutable, which means that we can change the content of the objects, which becomes handy for us in situations when we require to edit the contents of a string(character sequence). So, let’s consider an example through which, we can understand how to create a StringBuilder object.

public class Concatenation {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(“Gyani”);
sb.append(“Pandit”);
System.out.println(sb);
}
}

So, we could just change the content of the StringBuilder object using the append method from the StringBuilder class. There are some other methods as well, which can help us do different things like getting the length of the string, inserting some sequence of characters in the content, getting some character at the given index, and so on.

Here are some of the methods from the StringBuilder class –

Method nameDescription
length()As the name says, this method returns the length of the content(character sequence) in the specified StringBuilder object.
append(String str)Well, with this method, we can insert a given string at the end of the content of the StringBuilder object. Well, this method is overloaded so as to cover data types for the same purpose.
deleteCharAt(int index)Well, with this method, we are deleting the character present at the given index, from the content of the specified StringBuilder object.
insert(int offset, String str)With this method, we can insert some strings into the character sequence. The offset argument should be greater than or equal to zero, and less than or equal to the length of the specified sequence. The method is overloaded for other data types as well. We will see further as we see some examples.
indexOf(String str)This method returns the index of the first occurrence of the specified substring inside the character sequence. This method is also overloaded and takes another parameter from an index of int type, which helps us decide the starting point from where we need to check for the first occurrence of the substring in the sequence.
lastIndexOf(String str)This method returns the index of the last occurrence of the specified substring in the given character sequence. This method is also overloaded and takes another argument from the index, which is of int type, which helps us choose from where we want to search for the last occurrence of the substring in the given sequence.
reverse()As the name of the method says, this method replaces the character sequence with the reverse of the same sequence.
setCharAt(int index, char ch)With this method, we can set the character at the given index to ch.
capacity()Returns the current capacity. Well, just to mention that when we first create a StringBuilder with no characters in it, the initial capacity is 16 characters, and if the internal buffer overflows, the capacity is exceeded.
replace(int start, int end, String str)Replaces the character sequence from the start index to the end index(not included) with the given string
trim to size()This method helps us trim the size of the buffer, in case of extra buffer space, which is not required.

We are going to have a look at these methods one by one, but even before this, we are going to have a look at different constructors, which we can use when we are going to create StringBuilder objects. We can use those constructors as per our requirement.

Constructors of StringBuilder

Well, we have different constructors, when we are creating the StringBuilder. A constructor can be said as something that helps us initialize the object that is created.

First of all, have a look at the given program, in which, we are creating a StringBuilder with no characters in it. The initial capacity of the StringBuilder is 16 characters.

The constructor is written as like this → StringBuilder()

Lets now have a look on the below program, in which we are trying to use this constructor when we are creating the StringBuilder object is created-

public class SB {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());
}
}

So, it is clear from the above program, that initially, if we create the StringBuilder with no characters, the initial capacity is 16 characters.

Well, from the above constructor, the StringBuilder is created with the initial capacity of 16 characters. But what if we want to give the capacity ourselves? Well, for this, we have another constructor.

The constructor is something like this → String

Well, just by putting the initial capacity that we want as an argument to the constructor. Have a look at the below program, which explains the same –

public class SB {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(256);
System.out.println(sb.capacity());
}
}

If we try to execute the above program, the initial capacity is now found to be 256.

We have seen one of the constructors in the first program for StringBuilder, where we gave some string as an argument to the constructor so as to initialize the StringBuilder with the given content. Let’s have a look at the program again, where we are going to give a string to the constructor as an argument.

public class Concatenation {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(“GyaniPandit”);
System.out.println(sb);
}
}

As you can see, we could give the string as an argument to the constructor.