How to use Java’s StringBuilder
Java’s StringBuilder class can be used in place of traditional strings. Unlike traditional strings, StringBuilder allows you to make changes to a string without creating a new object. The changes can be made using different methods.
What is Java’s StringBuilder?
The string class in Java is immutable and doesn’t have any subclasses. One alternative to this final class is Java’s StringBuilder. It creates a sequence of characters that can be changed after it’s been created. In this way, Java’s StringBuilder is similar to StringBuffer. The two classes have a similar purpose, but unlike the buffer option StringBuilder is not synchronized. That makes StringBuilder a good choice when working with single threads, as it’s much faster than StringBuffer. In this tutorial, we’ll introduce you to StringBuilder in Java and show you some of its many uses.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
What is the syntax of Java’s StringBuilder?
The syntax of Java’s StringBuilder always follows the same pattern, which looks like this:
public final class StringBuilder
extends Object
implements Serializable, CharSequence
javaTo understand the basics of how the class works and what purpose it serves, it helps to first look at the traditional String class. Once you’ve declared an object in String, you can no longer change that object. If you want to make changes, you’ll need to create and save a whole new object. This creates a lot of data waste and can lead to decreased performance. If you use StringBuilder in Java instead, you can make changes to strings without creating a new one. This reduces waste and improves performance.
What are the constructors for Java’s StringBuilder?
Java’s StringBuilder has 4 constructors that help convert the string into the right format for the class. They are also used for configuration. Here are the four constructors and their purposes:
-
StringBuilder()
: Generates an empty StringBuilder with a maximum capacity of 16 characters -
StringBuilder(int capacity)
: Creates a StringBuilder without characters whose maximum capacity is defined using the capacity argument -
StringBuilder(CharSequence seq)
: Generates a string builder with the same characters as the stored char sequence -
StringBuilder(String str)
: Creates a StringBuilder with the string you enter
Let’s take a look at an example to see how these constructors work in practice:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder();
str.append("ABC");
System.out.println("First constructor = " + str.toString());
StringBuilder str2 = new StringBuilder(5);
System.out.println("Second constructor = " + str2.capacity());
StringBuilder str3 = new StringBuilder("ABCDEFGHIJK");
System.out.println("Third constructor = " + str3.toString());
StringBuilder str4 = new StringBuilder(str3.toString());
System.out.println("Fourth constructor = " + str4.toString());
}
}
javaWhen we use the Java command System.out.println
to get the output, we get the following:
First constructor = ABC
Second constructor = 5
Third constructor = ABCDEFGHIJK
Fourth constructor = ABCDEFGHIJK
javaWhich methods are used with StringBuilder in Java?
There are a number of methods that can be used with the Java’s StringBuilder class. Below we introduce some of the most important ones, with code examples.
append()
The append()
method is used to add one string to another. It has various parameters. Here’s how it works in practice:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder("ABCDE");
str.append("FGHIJK");
System.out.println(str);
}
}
javaThe output is as follows:
ABCDEFGHIJK
javainsert()
The insert()
method is used in combination with Java’s StringBuilder to insert a string at a specific point. Here’s an example for how it works:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder("ABCDE");
str.insert(1,"FGHIJK");
System.out.println(str);
}
}
javaHere’s the output:
AFGHIJKBCDEFGHIJK
javaThe integer (in this case 1) is used to define the position that the string will be inserted at.
replace()
The replace()
method replaces a string or part of a string. It’s defined using beginIndex
and endIndex
. This is how it works in practice:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder("ABCDE");
str.replace(1,4,"FGHIJK");
System.out.println(str);
}
}
javaThe output looks as follows:
AFGHIJKE
javareverse()
The reverse()
method is used to put the stored string in backwards order. Here’s how it works:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder("ABCDE");
str.reverse();
System.out.println(str);
}
}
javaHere’s the output:
EDCBA
javadelete()
You can use the delete()
method with Java’s StringBuilder to delete all or part of a string. If you want to delete part of the string, you can do it with beginIndex
and endIndex
.
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder("ABCDE");
str.delete(1,4);
System.out.println(str);
}
}
javaHere’s the output:
AE
javacapacity()
The capacity()
method gives you the current maximum character count for StringBuilder. It’s normally 16. If it is increased, that is usually done using the formula “current character count * 2 + 2”. So if it is currently 16, it will be multiplied by 2 (32) and then have 2 added to it. You can see that in our example:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder();
System.out.println(str.capacity());
str.append("ABCDE");
System.out.println(str.capacity());
str.append("This is another example");
System.out.println(str.capacity());
}
}
javaThe output looks as follows:
16
16
34
javaensureCapacity()
The ensureCapacity()
method ensures that the number of available characters is at least that of the defined value. If that’s not the case, the capacity will be increased using the formula from above, “current character count * 2 + 2”. You can see that in the following example:
public class Main {
public static void main(String[] argv) throws Exception {
StringBuilder str = new StringBuilder();
System.out.println(str.capacity());
str.append("ABCDE");
System.out.println(str.capacity());
str.append("This is another example");
System.out.println(str.capacity());
str.ensureCapacity(5);
System.out.println(str.capacity());
str.ensureCapacity(40);
System.out.println(str.capacity());
}
}
javaHere’s the output:
16
16
34
34
70
javaFirst we see the standard value (16), then that value multiplied by 2 and added to 2 (34), and finally that new value multiplied by 2 and added to 2.