Java StringBuilder tutorial

Learns the basics of Java StringBuilder with this tutorial.

StringBuilder is a mutable class (following builder pattern) that allows creation of strings composed from smaller strings. It is located in java.util package (import java.util.StringBuilder).

Creating StringBuilder objects

StringBuilder objects are created by instantiating StringBuilder class.

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("Initial string");

Using StringBuilder

The two most used and most important methods of StringBuilder are append and toString,

StringBuilder append(String str)

The append methods adds provided value to the end of current current string buffer. There are several overloaded append methods that accept any type of data.

StringBuilder sb = new StringBuilder();
sb.append("Hello! ");
sb.append("This is a number: ");
System.out.println(sb); // -> "Hello! This is a number: 3.14"

String toString()

Not surprisingly, toString returns StringBuilder as a string.

StringBuilder sb = new StringBuilder();
sb.append("Hello! ");
sb.append("This is a number: ");
String str = sb.toString();
System.out.println(str); // -> "Hello! This is a number: 3.14"

Chaining methods

Most of StringBuilder methods are returning reference to itself, making it possible to chain them.

String str = new StringBuilder()
     .append("Hello !")
     .append("This is a number: ")

System.out.println(str); // -> "Hello! This is a number: 3.14"

Other important StringBuilder methods

StringBuilder insert(int offset, String str)

Insert allows to insert provided string at a specified index in the StringBuilder. This method has several overloaded methods accepting all data types. If the index is less than zero or greater than length of StringBuilder then StringIndexOutOfBoundsException is thrown.

StringBuilder sb = new StringBuilder("I love cats");
sb.insert(7, "mice and ");
System.out.println(sb); // -> "I love mice and cats"

StringBuilder deleteCharAt(int index)

Removes a character at the specified index.

StringBuilder sb = new StringBuilder("Katze");
System.out.println(sb); // -> "Katz" (curiosity: it means "cat" in Bavarian)

StringBuilder delete(int start, int end)

Deletes a part of the string starting from position start (inclusive) to position end (exclusive).

StringBuilder sb = new StringBuilder("I am a big cat");
System.out.println(sb); // -> "I am a cat"

StringBuilder reverse()

Reverses the character sequence in StringBuilder

StringBuilder sb = new StringBuilder("Commodore C64");
System.out.println(sb); // -> "46C erodommoC"

StringBuilder methods similar to String methods

StringBuilder contains a set of methods working in the same way as in String. Those methods are length, indexOf, substring and charAt. Consult with my Java strings tutorial to learn how to use those methods.

Learn more about Java