Java’s String­Build­er class can be used in place of tra­di­tion­al strings. Unlike tra­di­tion­al strings, String­Build­er 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 String­Build­er?

The string class in Java is immutable and doesn’t have any sub­classes. One al­tern­at­ive to this final class is Java’s String­Build­er. It creates a sequence of char­ac­ters that can be changed after it’s been created. In this way, Java’s String­Build­er is similar to String­Buf­fer. The two classes have a similar purpose, but unlike the buffer option String­Build­er is not syn­chron­ised. That makes String­Build­er a good choice when working with single threads, as it’s much faster than String­Buf­fer. In this tutorial, we’ll introduce you to String­Build­er in Java and show you some of its many uses.

Web hosting
The hosting your website deserves at an un­beat­able price
  • Loading 3x faster for happier customers
  • Rock-solid 99.99% uptime and advanced pro­tec­tion
  • Only at IONOS: up to 500 GB included

What is the syntax of Java’s String­Build­er?

The syntax of Java’s String­Build­er always follows the same pattern, which looks like this:

public final class StringBuilder
	extends Object
		implements Serializable, CharSequence
java

To un­der­stand the basics of how the class works and what purpose it serves, it helps to first look at the tra­di­tion­al 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 per­form­ance. If you use String­Build­er in Java instead, you can make changes to strings without creating a new one. This reduces waste and improves per­form­ance.

What are the con­struct­ors for Java’s String­Build­er?

Java’s String­Build­er has 4 con­struct­ors that help convert the string into the right format for the class. They are also used for con­fig­ur­a­tion. Here are the four con­struct­ors and their purposes:

  • StringBuilder(): Generates an empty String­Build­er with a maximum capacity of 16 char­ac­ters
  • StringBuilder(int capacity): Creates a String­Build­er without char­ac­ters whose maximum capacity is defined using the capacity argument
  • StringBuilder(CharSequence seq): Generates a string builder with the same char­ac­ters as the stored char sequence
  • StringBuilder(String str): Creates a String­Build­er with the string you enter

Let’s take a look at an example to see how these con­struct­ors 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());
	}
}
java

When 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
java

Which methods are used with String­Build­er in Java?

There are a number of methods that can be used with the Java’s String­Build­er 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 para­met­ers. 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);
	}
}
java

The output is as follows:

ABCDEFGHIJK
java

insert()

The insert() method is used in com­bin­a­tion with Java’s String­Build­er 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);
	}
}
java

Here’s the output:

AFGHIJKBCDEFGHIJK
java

The 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);
	}
}
java

The output looks as follows:

AFGHIJKE
java

reverse()

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);
	}
}
java

Here’s the output:

EDCBA
java

delete()

You can use the delete() method with Java’s String­Build­er 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);
	}
}
java

Here’s the output:

AE
java

capacity()

The capacity() method gives you the current maximum character count for String­Build­er. 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 mul­ti­plied 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());
	}
}
java

The output looks as follows:

16
16
34
java

ensureCapacity()

The ensureCapacity() method ensures that the number of available char­ac­ters 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());
	}
}
java

Here’s the output:

16
16
34
34
70
java

First we see the standard value (16), then that value mul­ti­plied by 2 and added to 2 (34), and finally that new value mul­ti­plied by 2 and added to 2.

Go to Main Menu