Java StringBuilder tutorial with examples will help you understand how to use Java StringBuilder in an easy way. StringBuilder in Java is a mutable sequence of characters. Unlike String, the content of the StringBuilder can be changed after it is created using its methods.
The StringBuilder in Java extends from the Object class and implements Serializable, Appendable, and CharSequence interfaces. It is contained in java.lang package. The java.lang package is automatically imported into the code, so you do not have to import any package to use the StringBuilder class.
Difference between StringBuilder and StringBuffer
The StringBuilder class API is similar to that of the StringBuffer, with one difference. The StringBuilder in Java is not synchronized. That means you will have to take care of the synchronization if your code is trying to modify the contents of the StringBuilder using multiple threads.
However, if the code is single-threaded, you should prefer to use StringBuilder instead of the StringBuffer. The StringBuilder class gives better performance in comparison to the StringBuffer due to less overhead of the synchronization.
How to create new objects of StringBuilder in Java (StringBuilder Constructors)?
The StringBuilder class in Java provides several constructors to create new objects. The default no-argument constructor creates a new empty StringBuilder object having an initial capacity of 16 characters.
1 |
StringBuilder sb = new StringBuilder(); |
The overloaded StringBuilder constructor with a String argument allows us to create a StringBuilder object from the String object as given below.
1 2 3 4 5 |
String str = "Hello world"; //create StringBuilder object from String StringBuilder sb = new StringBuilder(str); System.out.println("StringBuilder contains: " + sb); |
Output
1 |
StringBuilder contains: Hello world |
The StringBuilder class also has an overloaded constructor that accepts the CharSequence argument. You can create a new StringBuilder object from the StringBuffer object using this constructor (in other words copy StringBuffer to StringBuilder object).
1 2 3 4 5 6 |
StringBuffer sbfr = new StringBuffer("StringBuffer contents"); //Convert StringBuffer to StringBuilder using this constructor StringBuilder sbld = new StringBuilder( sbfr ); System.out.println("StringBuilder contains: " + sbld); |
Output
1 |
StringBuilder contains: StringBuffer contents |
There is also an overloaded constructor that accepts the initial capacity of the StringBuilder object which I will talk about at the end of this tutorial.
How to append content to StringBuilder using the append method?
The StringBuilder class provides several overloaded append
methods using which we can append the content of the different data types to the StringBuilder object. The append
method has been overloaded to accept boolean, char, character array, CharSequence, double, float, int, long, Object, String, and StringBuffer types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
//append char to StringBuilder char ch = 'a'; StringBuilder sb1 = new StringBuilder(); sb1.append(ch); System.out.println("append char: " + sb1); //append boolean to StringBuilder boolean b = false; StringBuilder sb2 = new StringBuilder(); sb2.append(b); System.out.println("append boolean: " + sb2); //append int to StringBuilder int i = 1; StringBuilder sb3 = new StringBuilder(); sb3.append(i); System.out.println("append int: " + sb3); //append long to StringBuilder long l = 23l; StringBuilder sb4 = new StringBuilder(); sb4.append(l); System.out.println("append long: " + sb4); //append float to StringBuilder float f = 9.99f; StringBuilder sb5 = new StringBuilder(); sb5.append(f); System.out.println("append float: " + sb5); //append double to StringBuilder double d = 3.33; StringBuilder sb6 = new StringBuilder(); sb6.append(d); System.out.println("append double: " + sb6); //append String to StringBuilder String str = "String"; StringBuilder sb7 = new StringBuilder(); sb7.append(str); System.out.println("append String: " + sb7); //append StringBuffer to StringBuilder StringBuffer sbf = new StringBuffer("StringBuffer"); StringBuilder sb8 = new StringBuilder(); sb8.append(sbf); System.out.println("append StringBuffer: " + sb8); //append char array to StringBuilder char charArray[] = {'c', 'h', 'a', 'r', 'a', 'r', 'r', 'a', 'y'}; StringBuilder sb9 = new StringBuilder(); sb9.append(charArray); System.out.println("append char array: " + sb9); /* * If you want to append partial character array to StringBuilder, you * can specify the start index and length along with the character array */ char charArray1[] = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'}; StringBuilder sb10 = new StringBuilder(); sb10.append(charArray1, 0, 5); System.out.println("append partial char array: " + sb10); /* * If you want to append partial String, StringBuffer or * StringBuilder content to StringBuilder object, you can use * append(CharSequence s, int start, int end) method. */ String str1 = "Hello world"; StringBuilder sb11 = new StringBuilder(); //this will append string starting from index 6 till end to StringBuilder sb11.append(str1, 6, str1.length()); System.out.println("append partial string: " + sb11); |
Output
1 2 3 4 5 6 7 8 9 10 11 |
append char: a append boolean: false append int: 1 append long: 23 append float: 9.99 append double: 3.33 append String: String append StringBuffer: StringBuffer append char array: chararray append partial char array: hello append partial string: world |
How to insert content to StringBuilder using the insert method?
The insert
method of the StringBuilder class inserts specified data into the StringBuilder content at the specified position. Just like the append
method, the insert method is overloaded for boolean, char, character array, int, long, double, float, String, Object, and CharSequence types.
The below given example shows how to insert a String into the StringBuilder object.
1 2 3 4 5 6 7 8 9 10 11 |
StringBuilder sbld = new StringBuilder("Java Examples"); String str = "StringBuilder Tutorial With "; /* * To insert String to StringBuilder, use the insert method * and specify the index */ //this will insert String to StringBuilder at index 5 of StringBuilder sbld.insert(5, str); System.out.println("StringBuilder contains: " + sbld); |
Output
1 |
StringBuilder contains: Java StringBuilder Tutorial With Examples |
If you want to insert a substring of String to StringBuilder instead of the whole string, you can use the overloaded insert
method as given below.
1 2 3 4 5 6 7 8 9 10 11 |
StringBuilder sbld = new StringBuilder("Java Examples"); String str = "StringBuilder Tutorial With "; /* * This will insert substring of string starting * from index 0 and length of 14 to StringBuilder * at index 5 */ sbld.insert(5, str, 0, 14); System.out.println("StringBuilder contains: " + sbld); |
Output
1 |
StringBuilder contains: Java StringBuilder Examples |
How to insert at front of the StringBuilder (beginning of the StringBuilder)?
Specify the index as 0 to insert the content at the front of the StringBuilder or at the beginning of the StringBuilder object.
1 2 3 4 5 6 7 8 9 |
StringBuilder sbld = new StringBuilder(" Examples"); String str = "Java"; /* * This will insert string at the beginning of the StringBuilder */ sbld.insert(0, str); System.out.println("StringBuilder contains: " + sbld); |
Output
1 |
StringBuilder contains: Java Examples |
How to get the character at the specified index of StringBuilder using the charAt method?
The charAt
method of the StringBuilder class returns a character in the StringBuilder at the specified index.
1 2 3 4 5 6 7 8 9 |
StringBuilder sbld = new StringBuilder("Hello World"); /* * The charAt method returns character at the * specified index of the StringBuilder */ System.out.println("get first character of StringBuilder: " + sbld.charAt(0)); System.out.println("get last character of StringBuilder: " + sbld.charAt( sbld.length() - 1 )); |
Output
1 2 |
get first character of StringBuilder: H get last character of StringBuilder: d |
The specified index must be greater than or equal to zero and less than the StringBuilder length. The charAt
method throws IndexOutOfBoundsException if the specified index is negative or it is greater than or equal to the length of the StringBuilder object.
How to get the length of the StringBuilder (size of StringBuilder) using the length method?
The StringBuilder length
method returns the number of characters contained in the StringBuilder object. It returns zero if the StringBuilder is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
StringBuilder sbld = new StringBuilder(""); /* * The length method returns number of characters * contained in the StringBuilder object. */ //this will return 0 as the StringBuilder is empty System.out.println( "StringBuilder length: " + sbld.length() ); sbld.append("hello"); //this will return 5 as the StringBuilder contains 5 characters System.out.println( "StringBuilder length: " + sbld.length() ); |
Output
1 2 |
StringBuilder length: 0 StringBuilder length: 5 |
How to delete characters from StringBuilder using the delete and deleteCharAt methods?
The deleteCharAt
method deletes a character in the StringBuilder at the specified index.
1 2 3 4 5 6 7 8 9 10 11 |
StringBuilder sbld = new StringBuilder("There here"); /* * The deleteCharAt method deletes a character from the * StringBuilder at the specified index */ System.out.println("delete first character of StringBuilder: " + sbld.deleteCharAt(0)); System.out.println("delete last character of StringBuilder: " + sbld.deleteCharAt( sbld.length() - 1 )); System.out.println("StringBuilder contains: " + sbld); |
Output
1 2 3 |
delete first character of StringBuilder: here here delete last character of StringBuilder: here her StringBuilder contains: here her |
The deleteCharAt
method throws StringIndexOutOfBoundsException if the specified index is negative or it is greater than or equal to the length of the StringBuilder object.
How to delete substring from StringBuilder?
The delete
method of the StringBuilder class deletes a substring from this StringBuilder object.
1 |
public StringBuilder delete(int startIndex, int endIndex) |
The startIndex is inclusive while the endIndex is exclusive. If the startIndex is equal to endIndex, no changes are made to the StringBuilder object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
StringBuilder sbld = new StringBuilder("StringBuilder Tutorial"); /* * The delete method deletes substring from StringBuilder * starting at specified start index and ending at * the specified end index - 1 */ //this will delete characters from 0 to 13 sbld.delete(0, 14); System.out.println("StringBuilder contains: " + sbld); /* * This will delete all characters from StringBuilder * i.e. make StringBuilder empty or clear */ sbld.delete(0, sbld.length()); System.out.println("StringBuilder contains: " + sbld); |
Output
1 2 |
StringBuilder contains: Tutorial StringBuilder contains: |
The delete
method throws StringIndexOutOfBoundsException if the start index is less than zero, greater than the length, or greater than the end index.
How to copy characters from StringBuilder to an array using the getChars method?
The StringBuilder getChars
method copies characters from StringBuilder object starting and ending at the specified index to the specified character array.
1 |
public void getChars(int srcIndexStart, srcIndexEnd, char[] array, int arrayStartIndex) |
The srcIndexStart is inclusive while the srcIndexEnd is exclusive. The total number of characters to be copied to the array is srcIndexEnd – srcIndexStart. The characters are copied to the array starting from the arrayStartIndex index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
char[] charArray = new char[10]; //fill char array with 0 Arrays.fill(charArray, '0'); System.out.println("char array contains: "); System.out.println(charArray); StringBuilder sbld = new StringBuilder("Java StringBuilder Examples"); /* * To copy characters from StringBuilder to char array, * use the getChars method */ //this will copy characters from index 5 to 10 to array at index 1 sbld.getChars(5, 11, charArray, 1); System.out.println("char array contains: "); System.out.println(charArray); |
Output
1 2 3 4 |
char array contains: 0000000000 char array contains: 0String000 |
The getChars
method throws IndexOutOfBoundsException if the srcIndexStart or srcIndexEnd index is negative, srcIndexStart is greater than the srcIndexEnd index, srcIndexEnd index is greater than the StringBuilder length, or arrayStartIndex + (srcIndexEnd – srcIndexStart) is greater than the array length.
How to search substring in StringBuilder using the indexOf and lastIndexOf methods?
How to search the first occurrence of a substring in StringBuilder?
The StringBuilder indexOf
method returns the first occurrence of the specified substring within this StringBuilder. It returns -1 if the StringBuilder does not contain the specified substring.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
StringBuilder sbld = new StringBuilder("Hello World"); /* * To search substring in StringBuilder, use the indexOf method. */ //this will return 0 as Hello starts at index 0 in the StringBuilder System.out.println( "Index of hello: " + sbld.indexOf("Hello") ); //this will return 8 as Hello starts at index 8 in the StringBuilder System.out.println( "Index of rld: " + sbld.indexOf("rld") ); //this will return -1 as the StringBuilder does not contain Hi System.out.println( "Index of Hi: " + sbld.indexOf("Hi") ); |
Output
1 2 3 |
Index of hello: 0 Index of rld: 8 Index of Hi: -1 |
If you want to search for a substring after the specified index of the StringBuilder, use the overloaded indexOf
method and specify the start index as given below.
1 2 3 4 5 6 |
StringBuilder sbld = new StringBuilder("Hello World"); System.out.println("Index of o: " + sbld.indexOf("o")); //this will print index of "o" after index 5 i.e. index 7 System.out.println("Index of o after index 5: " + sbld.indexOf("o", 5)); |
Output
1 2 |
Index of o: 4 Index of o after index 5: 7 |
How to search the last occurrence of a substring in StringBuilder?
The StringBuilder lastIndexOf
method returns the index of the last occurrence of the specified substring within the StringBuilder object. If the substring is not found, it returns -1.
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuilder sbld = new StringBuilder("First second comes after second second"); /* * The lastIndexOf method returns the index of the last occurrence * of the given substring within the StringBuilder object */ //this will print 32 as it it the index of last occurrence of "second" substring System.out.println( "last index of second: " + sbld.lastIndexOf("second") ); //this will return -1 as StringBuilder does not contain "third" System.out.println( "last index of third: " + sbld.lastIndexOf("third") ); |
Output
1 2 |
last index of second: 32 last index of third: -1 |
If you want to search the last occurrence of the substring from the given index, use the overloaded lastIndexOf
method as given below.
1 2 3 4 5 6 7 8 9 10 |
StringBuilder sbld = new StringBuilder("First second comes after second second"); //this will print 32, i.e. the last index of "second" System.out.println( "last index of second: " + sbld.lastIndexOf("second") ); //this will print 25, i.e. the last index of "second" before index 31 searching backwards System.out.println( "last index of second after index 31: " + sbld.lastIndexOf("second", 31) ); //this will print 4, i.e. the last index of "second" before index 24 searching backwards System.out.println( "last index of second after index 31: " + sbld.lastIndexOf("second", 24) ); |
Output
1 2 3 |
last index of second: 32 last index of second after index 31: 25 last index of second after index 31: 6 |
How to change the length of the StringBuilder using the setLength method?
The StringBuilder setLength
method sets the length of this StringBuilder object. If the new length is greater than the StringBuilder length, the rest of the characters will be filled by a null character (i.e. ‘\u0000’). If the new length is less than the StringBuilder length, the rest of the characters are truncated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
StringBuilder sbld = new StringBuilder("Hello World"); System.out.println("StringBuilder length: " + sbld.length()); /* * The setLength method sets the length of the StringBuilder * to the specified new length */ /* * This will make StringBuilder length equal to 5, will truncate * all characters after index 4 (index 0 to 4 = length of 5) */ sbld.setLength(5); System.out.println("After truncating length"); System.out.println("StringBuilder length: " + sbld.length()); System.out.println("StringBuilder contains: " + sbld); /* * Similarly, if you set new length which is greater * than the StringBuilder's existing length, the rest * of the characters are filled with null characters */ //this will expand StringBuilder to lenth of 10 sbld.setLength(10); System.out.println("After expanding length"); System.out.println("StringBuilder length: " + sbld.length()); System.out.println("StringBuilder contains: " + sbld); |
Output
1 2 3 4 5 6 7 |
StringBuilder length: 11 After truncating length StringBuilder length: 5 StringBuilder contains: Hello After expanding length StringBuilder length: 10 StringBuilder contains: Hello |
The setLength
method throws IndexOutOfBoundsException if the specified new length is negative.
How to check if the StringBuilder is empty?
You can use the length
method and compare it with zero to check if the StringBuilder is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
StringBuilder sbld = new StringBuilder(); if(sbld.length() == 0) System.out.println("StringBuilder is empty"); else System.out.println("StringBuilder is not empty"); sbld.append("Hello"); if(sbld.length() == 0) System.out.println("StringBuilder is empty"); else System.out.println("StringBuilder is not empty"); |
Output
1 2 |
StringBuilder is empty StringBuilder is not empty |
Please visit the full example of how to check if StringBuilder is empty example to know more.
How to empty or clear the StringBuilder?
Use the setLength
method to empty the StringBuilder content as given below.
1 2 3 4 5 6 7 8 9 10 |
StringBuilder sbld = new StringBuilder("Hello world"); System.out.println( "Is StringBuilder empty? " + (sbld.length() == 0) ); /* * To clear the StringBuilder content use the setLength method */ sbld.setLength(0); System.out.println( "Is StringBuilder empty? " + (sbld.length() == 0) ); System.out.println("StringBuilder contains: " + sbld); |
Output
1 2 3 |
Is StringBuilder empty? false Is StringBuilder empty? true StringBuilder contains: |
There are three options to clear or empty the StringBuilder object. Please visit the full example of how to empty StringBuilder to know what are they and what is the best way to empty the StringBuilder object.
How to replace a character at the specified index of StringBuilder using the setCharAt method?
The StringBuilder setCharAt
method replaces the current character at the given index with the specified new character.
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuilder sbld = new StringBuilder("Cat"); System.out.println("StringBuilder contains: " + sbld); /* * The setCharAt method replaces old character with new * character at given index of the StringBuilder */ //this will replace 'C' (i.e. character at index 0) with 'B' sbld.setCharAt(0, 'B'); System.out.println("StringBuilder contains: " + sbld); |
Output
1 2 |
StringBuilder contains: Cat StringBuilder contains: Bat |
The setCharAt
method throws IndexOutOfBoundsException if the specified index is negative, or greater than or equal to the length of the StringBuilder.
How to replace a substring in StringBuilder using the replace method?
The StringBuilder replace
method replaces substring within this StringBuilder object with the given String at the specified start and end index.
1 |
public StringBuilder replace(int startIndex, int endIndex, String replacement) |
The startIndex is inclusive, while the endIndex is exclusive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
StringBuilder sbld = new StringBuilder("I like C++"); /* * To replace a substring in the StringBuilder, use * the replace method */ /* * this will replace substring starting from * index 7 and ending at index 9 (i.e. C++) with * string "Java" */ sbld.replace(7, 10, "Java"); System.out.println("StringBuilder contains: " + sbld); |
Output
1 |
StringBuilder contains: I like Java |
If the specified endIndex index is greater than the length of the StringBuilder, the replacement will be done till the end of the StringBuilder content. The replace
method throws StringIndexOutOfBoundsException if the start index is negative, greater than the StringBuilder length, or greater than the end index.
How to reverse the StringBuilder using the reverse method?
The StringBuilder reverse
method replaces StringBuilder’s content with the reverse of the content.
1 2 3 4 5 6 |
StringBuilder sbld = new StringBuilder("StringBuilder reverse"); /* * To reverse StringBuilder, use the reverse method */ System.out.println( sbld.reverse() ); |
Output
1 |
esrever redliuBgnirtS |
How to get a substring from StringBuilder using the substring method?
The StringBuilder substring
method returns a substring from the StringBuilder starting at the specified index till the end of the content.
1 |
public String substring(int startIndex) |
Here, the startIndex is inclusive.
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuilder sbld = new StringBuilder("StringBuilder substring"); /* * To get substring from StringBuilde, use the * substring method */ /* * this will return substring from StringBuilder starting * at index 14 till StringBuilder length i.e. "substring" */ System.out.println( sbld.substring(14) ); |
Output
1 |
substring |
This method throws StringIndexOutOfBoundsException if the start index is negative or greater than the StringBuilder length.
Use an overloaded substring
method if you want to take substring starting and ending at the specified index.
1 2 3 4 5 6 7 |
StringBuilder sbld = new StringBuilder("StringBuilder substring"); /* * this will return substring from StringBuilder starting * at index 14 and ending at index 16 (end index is exclusive) */ System.out.println( sbld.substring(14, 17) ); |
Output
1 |
sub |
This method throws StringIndexOutOfBoundsException if the start index or end index is negative, if the end index is greater than the StringBuilder length, or the start index is greater than the end index.
How to get a substring from StringBuilder using the subSequence method?
The StringBuilder subSequence
method returns a new String containing the substring from this StringBuilder object starting and ending at the specified index.
1 |
public CharSequence subSequence(int startIndex, int endIndex) |
This method behaves in the same way as the substring
method, the only difference is this method returns CharSequence while the substring
method returns a String object. This method is provided so that the StringBuilder class can implement the CharSequence interface.
How to convert StringBuilder to String using the toString method?
The StringBuilder toString
method returns a string representation of this StringBuilder object. A new String object is created containing the content of this StringBuilder object and returned.
1 2 3 4 5 6 7 8 9 |
StringBuilder sbld = new StringBuilder("Convert StringBuilder to String"); /* * To convert StringBuilder to String, use the * toString method */ String string = sbld.toString(); System.out.println("String contains: " + string); |
Output
1 |
String contains: Convert StringBuilder to String |
How to copy one StringBuilder object to another StringBuilder object?
You can use the StringBuilder constructor to copy one StringBuilder to another as given below.
1 2 3 4 5 6 7 8 9 |
StringBuilder sbld = new StringBuilder("StringBuilder copy"); /* * To copy one StringBuilder to another, use * the constructor */ StringBuilder sbldCopy = new StringBuilder(sbld); System.out.println("Copied StringBuilder contains: " + sbldCopy ); |
Output
1 |
Copied StringBuilder contains: StringBuilder copy |
You can also use the same constructor to copy StringBuffer to the StringBuilder object.
1 2 3 4 5 6 7 8 9 |
StringBuilder sbld = new StringBuilder("Convert StringBuilder to StringBuffer"); /* * To copy or convert StringBuilder to StringBuffer, use * the same constructor */ StringBuffer sbf = new StringBuffer( sbld ); System.out.println("StringBuffer contains: " + sbf ); |
Output
1 |
StringBuffer contains: Convert StringBuilder to StringBuffer |
The StringBuilder append
method can be used as well to copy as given below.
1 2 3 4 5 6 |
StringBuilder sbld = new StringBuilder("Hello World"); StringBuilder sbldCopy = new StringBuilder(); sbldCopy.append(sbld); System.out.println("Copied StringBuilder contains: " + sbldCopy ); |
Output
1 |
Copied StringBuilder contains: Hello World |
What is StringBuilder capacity and how to manage it efficiently?
The StringBuilder class internally manages an array to store its contents. The length of this array is called StringBuilder capacity. The capacity of the StringBuilder is automatically increased as we add more content to it. The StringBuilder class does this by allocating a new internal array with the required length. The default capacity of the StringBuilder object is 16.
In normal scenarios, we do not need to worry about the capacity of the StringBuilder object. However, if you are planning to add a large amount of data to StringBuilder, it needs to allocate a new internal array very frequently to fit the content which is a very costly operation in terms of performance.
In such cases, you can create a StringBuilder object with the desired approximate capacity to avoid frequent new array allocation. For example, if you want to store approximately 10000 characters in the StringBuilder, you can allocate that much space upfront using the below-given constructor.
1 2 3 4 5 |
/* * This will create a StringBuilder object with the * capacity of 10000. */ StringBuilder sbld = new StringBuilder(10000); |
You can get the current capacity of the StringBuilder object using the capacity
method. If you want to change the capacity of the existing StringBuilder object, use the ensureCapacity
method.
1 |
public void ensureCapacity(int minimumCapacity) |
This method ensures that the StringBuilder capacity is at least equal to the specified minimum capacity. If the specified minimum capacity is greater than the current capacity, this method allocates a new internal array with a new capacity that is larger of the specified minimum capacity or (old capacity * 2) + 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
StringBuilder sbld = new StringBuilder(); //get the current capacity of the StringBuilder System.out.println("StringBuilder default capacity: " + sbld.capacity()); /* * To increase the capacity, use the ensureCapacity method */ /* * This will increase the StringBuilder capacity to 34. * Larger of 32 and (16 * 2) + 2 = 34 */ sbld.ensureCapacity(32); System.out.println("StringBuilder capacity: " + sbld.capacity()); /* * This will increase the StringBuilder capacity to 100. * Larger of 100 and (34 * 2) + 2 = 70 */ sbld.ensureCapacity(100); System.out.println("StringBuilder capacity: " + sbld.capacity()); |
Output
1 2 3 |
StringBuilder default capacity: 16 StringBuilder capacity: 34 StringBuilder capacity: 100 |
It is a good practice to allocate the approximate capacity to the StringBuilder object before adding large data to it. The performance improvement is noticeable if the capacity is allocated as per the size of the data that needs to be inserted into the StringBuilder object.
Once increased, the StringBuilder capacity does not decrease automatically if you store less content later on. So for example, if you have allocated 10000 capacity to StringBuilder object but later on you do not need this much capacity, you need to decrease it using the trimToSize
method. This method tries to allocate a new internal array of the smaller size required to fit the StringBuilder content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
StringBuilder sbld = new StringBuilder(10000); sbld.append("StringBuilder"); System.out.println("StringBuilder capacity: " + sbld.capacity()); //insert and process large data here... /* * If you application does not need the increased capacity * anymore, you can reduce the storage space taken up by the * internal array using the trimToSize method */ sbld.trimToSize(); System.out.println("StringBuilder new capacity: " + sbld.capacity()); |
Output
1 2 |
StringBuilder capacity: 10000 StringBuilder new capacity: 13 |
Below given are some of the Java StringBuilder examples which show how to use StringBuilder in Java.
Java StringBuilder Examples
- How to add content to the front of the StringBuilder object (at the beginning)
- How to append a new line to StringBuilder object
- How to replace the content of the StringBuilder (StringBuilder replaceAll method)
- How to check if StringBuilder object contains text or String
- How to empty StringBuilder object (clear contents of StringBuilder)
- How to check if StringBuilder object is empty
- How to convert StringBuilder to String object and String to StringBuilder object
- How to remove the last character of the StringBuilder object
- How to get the StringBuilder length
- What is StringBuilder capacity
- How to compare two StringBuilder objects by content
References:
Java StringBuilder class Javadoc
Please let me know if you liked the Java StringBuilder tutorial with examples in the comments section below.