Java StringBuilder Syntax
StringBuilder is a class in the java.lang package. The append() and insert() methods take a value of any type, such as a string, a number or a character. Both return the same StringBuilder, so calls can be chained.
What is the difference between String, StringBuilder and StringBuffer?
A String cannot be changed after it is created. StringBuilder and StringBuffer change their content in place. StringBuffer is synchronized and safe to share between threads. StringBuilder is not, and in a single thread it is faster.
Java StringBuilder Examples
The following are examples of using StringBuilder in Java. You can run any of these examples in the online Java code runner to see the text after each change.
Build a string with append()
append() adds each value to the end of the same object, so the loop works with one StringBuilder instead of creating a new String on every pass.
Insert, replace and delete characters
Indexes start at 0. In replace() and delete(), the start index is inclusive and the end index is exclusive.
Reverse a string with reverse()
reverse() turns the characters around in place. A word that reads the same after reverse() is a palindrome.
Get the length of a StringBuilder
length() returns the current number of characters, and charAt() reads the character at an index. setLength(4) keeps the first four characters.