Java StringBuffer tutorial with examples will help you understand how to use the Java StringBuffer class in an easy way. StringBuffer in Java is a mutable sequence of characters. The difference between String and StringBuffer is that the StringBuffer is mutable while String is immutable. it means that the StringBuffer object’s content can be changed or modified using its methods.
The StringBuffer class in Java is a thread-safe implementation, which means that if multiple threads are trying to modify the contents of the string buffer at the same time, the StringBuffer class takes care of the synchronization.
The Java StringBuffer class extends from the Object class and implements Serializable, Appendable, and CharSequence interfaces. It is contained in the 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 StringBuffer class.
How to create a new StringBuffer object?
The StringBuffer class in Java provides several constructors to create new objects. The default constructor creates a new empty StringBuffer object with the initial capacity of 16.
1 |
StringBuffer sb = new StringBuffer(); |
If you want to create a StringBuffer object from the existing object of String, StringBuffer, or StringBuilder class, use the constructor with the CharSequence argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//String to StringBuffer String str = "String to StringBuffer"; StringBuffer sb1 = new StringBuffer(str); System.out.println( sb1 ); //StringBuilder to StringBuffer StringBuilder sbld = new StringBuilder("StringBuilder to StringBuffer"); StringBuffer sb2 = new StringBuffer(sbld); System.out.println( sb2 ); //copy StringBuffer to another StringBuffer StringBuffer sbOriginal = new StringBuffer("Copy StringBuffer to another StringBuffer"); StringBuffer sbCopy = new StringBuffer(sbOriginal); System.out.println( sbCopy ); |
Output
1 2 3 |
String to StringBuffer StringBuilder to StringBuffer Copy StringBuffer to another StringBuffer |
The capacity of the StringBuffer object will be 16 + the length of the character sequence given in the argument.
How to get StringBuffer length using the length method?
The length
method of the StringBuffer class returns the number of characters currently stored in the object.
1 2 3 4 5 6 7 8 9 |
StringBuffer sb = new StringBuffer(); //this will print 0 because StringBuffer is empty System.out.println( sb.length() ); sb = new StringBuffer("String"); //this will print 6, i.e. number of characters System.out.println( sb.length() ); |
Output
1 2 |
0 6 |
How to set StringBuffer length using the setLength method?
The setLength
method sets the length of the character sequence of this StringBuffer object.
1 |
public void setLength(int newLength) |
If the new length is greater than or equal to the current length of the StringBuffer, then ‘\u0000’ (null characters) is appended at the end of the character sequence so that the current length becomes the new length. If the new length is less than the current length, the current length is changed to the new length by discarding the characters from the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
StringBuffer sb = new StringBuffer("Hello"); System.out.println("Current length: " + sb.length()); /* * This will increase the length of the StringBuffer * object to 10 by appending 5 null characters * at the end */ sb.setLength(10); System.out.println("new legth: " + sb.length()); StringBuffer sb1 = new StringBuffer("Java StringBuffer Examples"); System.out.println("Current length: " + sb1.length()); /* * This will decrease the length of the StringBuffer * by removing characters from the end */ sb1.setLength(4); System.out.println("new length: " + sb1.length()); System.out.println("StringBuffer contains: " + sb1); |
Output
1 2 3 4 5 |
Current length: 5 new legth: 10 Current length: 26 new length: 4 StringBuffer contains: Java |
How to append content to the StringBuffer object using the append method?
The append
method appends the specified argument at the end of the StringBuffer content. The append
method is overloaded to accept char, char array, boolean, 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 |
StringBuffer sb = new StringBuffer(""); //append boolean to StringBuffer boolean b = false; sb.append(b); //append int int i = 100; sb.append(i); //append long long l = 23l; sb.append(l); //append float float f = 4.2f; sb.append(f); //append double double d = 2.54; sb.append(d); System.out.println(sb); //append String to StringBuffer StringBuffer sb1 = new StringBuffer("StringBuffer"); String str = " String Content"; sb1.append(str); System.out.println(sb1); //append content of another StringBuffer or StringBuilder StringBuffer sb2 = new StringBuffer("StringBuffer content"); StringBuffer sb3 = new StringBuffer(" Another StringBuffer content"); sb2.append(sb3); System.out.println(sb2); |
Output
1 2 3 |
false100234.22.54 StringBuffer String Content StringBuffer content Another StringBuffer content |
How to append a substring of String to StringBuffer object?
The above given example appends the full content of the String or StringBuffer object to another StringBuffer object. If you want to append a substring instead of the full string, use the below given overloaded append
method.
1 |
StringBuffer append(CharSequence sequence, int startIndex, int endIndex) |
This method appends the content of the specified objects substring starting from the start index and ending at the end index to this StringBuffer object. Since this method accepts the CharSequence reference, you can use String, StringBuffer, or StringBuilder object. Plus, the start index is inclusive, while the end index is exclusive.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str = "Java StringBuffer Tutorial"; StringBuffer sb = new StringBuffer(); /* * Specify start and end index * to append the substring * * Start index is inclusive, * end index is exclusive */ sb.append(str, 18, 26); System.out.println(sb); |
Output
1 |
Tutorial |
How to insert content into the StringBuffer object using the insert method?
The insert
method of the StringBuffer class inserts the specified argument string at the given index of the StringBuffer object. Just like the append
method, the insert
method is also overloaded for boolean, char, char array, CharSequence, double, float, int, long, and String types. Let’s have a look at the insert
method with the String argument.
1 |
StringBuffer insert(int index, String str) |
This method inserts the string into the StringBuffer at the specified index.
1 2 3 4 5 6 7 |
StringBuffer sb = new StringBuffer("StringBuffer examples"); String str = "Java "; //this will insert String into StringBuffer at index 0 sb.insert(0, str); System.out.println(sb); |
Output
1 |
Java StringBuffer examples |
If you want to insert the substring of String, StringBuffer, or StringBuilder object into the StringBuffer, use below given overloaded insert
method.
1 |
StringBuffer insert(int index, CharSequence sequence, int start, int end) |
This method inserts the substring of the specified CharSequence starting from the start and ending at the end index to this StringBuffer object at the specified index. The start index is inclusive, while the end index is exclusive.
1 2 3 4 5 6 7 8 9 10 11 |
String str = "Hello world"; StringBuffer sb = new StringBuffer("Java"); /* * This will insert substring of the string str * starting at 5 index, ending at 10 * to the StringBuffer at the index 4 */ sb.insert(4, str, 5, 11); System.out.println(sb); |
Output
1 |
Java world |
How to get a character from the StringBuffer using the charAt method?
The charAt
method of the StringBuffer class returns a character stored at the specified index of the StringBuffer object. The index is 0 based, so the first character is at index 0 and the last character is located at StringBuffer length – 1 index.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
StringBuffer sb = new StringBuffer("charAt method"); //this will get first character from the StringBuffer i.e. c char c1 = sb.charAt(0); System.out.println(c1); //this will get the 8th character from the StringBuffer i.e. m char c2 = sb.charAt(7); System.out.println(c2); //this will get the last character from the StringBuffer i.e. d char c3 = sb.charAt( sb.length() - 1 ); System.out.println(c3); |
Output
1 2 3 |
c m d |
The charAt
method throws IndexOutOfBoundsException
if the given index is negative or is greater than or equal to the length of the StringBuffer object.
How to replace a character in the StringBuffer object using the setCharAt method?
The setCharAt
method replaces a character at the specified index with the given new replacement character.
1 2 3 4 5 6 7 8 9 |
StringBuffer sb = new StringBuffer("String"); /* * This will replace the character * at index 3, i.e. character 4 * in the StringBuffer */ sb.setCharAt(3, 'o'); System.out.println(sb); |
Output
1 |
Strong |
The setCharAt
method throws IndexOutOfBoundsException
if the specified index is negative or is greater than or equal to StringBuffer length.
How to replace a substring in StringBuffer using the replace method?
The replace
method replaces the substring of this StringBuffer with the specified replacement string.
1 |
StringBuffer replace(int startIndex, int endIndex, String replacement) |
The start index is inclusive and the endIndex is exclusive i.e. the replacement starts at the startIndex and ends at endIndex – 1.
Example:
1 2 3 4 5 6 7 8 9 |
StringBuffer sb = new StringBuffer("I love c++ programming"); /* * characters at index 7, 8 and 9 * will be replaced with Java */ sb.replace(7, 10, "Java"); System.out.println(sb); |
Output
1 |
I love Java programming |
The replace method throws StringIndexOutOfBoundsException
if the startIndex is negative, or greater than the length of the StringBuffer, or greater than the endIndex.
How to get a substring from StringBuffer using the substring method?
The substring
method returns a new String object containing the subsequence starting at the specified index to the end of the StringBuffer content.
1 |
public String substring(int startIndex) |
Example:
1 2 3 4 5 6 |
StringBuffer sb = new StringBuffer("Java StringBuffer Tutorial"); //this will get the substring starting from index 5 till end String substring = sb.substring(5); System.out.println(substring); |
Output
1 |
StringBuffer Tutorial |
The above method gets the substring starting from the specified index and ending at the StringBuffer’s length. If you want to get the substring starting and ending at the specified index, use an overloaded substring
method having start and end index parameters.
1 |
public String substring(int startIndex, int endIndex) |
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("StringBuffer in Java"); /* * This will take substring from StringBuffer * starting at index 13 to index 14 */ String substring = sb.substring(13, 15); System.out.println(substring); |
Output
1 |
in |
This method throws IndexOutOfBoundsException
if the start or end index is negative or greater than the length, or the start index is greater than the end index.
How to get a substring from StringBuffer using the subSequence method?
The subSequence
method returns a new character sequence that is a subsequence of this StringBuffer object, starting and ending at the specified index.
1 |
public CharSequence subSequence(int startIndex, int endIndex) |
This method is exactly the same as the substring
method except for the return type. The substring
method returns a String object while the subSequence
method returns a CharSequence. The subSequence
method is provided just because the StringBuffer class implements the CharSequence interface.
1 2 3 4 5 6 7 8 9 10 |
StringBuffer sb = new StringBuffer("StringBuffer in Java"); /* * This will take substring from StringBuffer * starting at index 0 to index 11. * * This is same as substring method. */ CharSequence substring = sb.subSequence(0, 12); System.out.println(substring); |
Output
1 |
StringBuffer |
How to delete a character or substring from the StringBuffer?
1. How to delete a character from the StringBuffer using the deleteCharAt method?
The deleteCharAt
method deletes a character from the StringBuffer at the specified index.
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("Java"); /* * This will delete character at index 1 * i.e. character 2 ('a') */ sb.deleteCharAt(1); System.out.println(sb); |
Output
1 |
Jva |
This method throws StringIndexOutOfBoundsException
if the index is negative or greater than or equal to the StringBuffer length.
2. How to delete a substring from the StringBuffer using the delete method?
The delete
method deletes a substring from the StringBuffer starting and ending at the specified index.
1 |
StringBuffer delete(int startIndex, int endIndex) |
The substring starts with the startIndex and ends at endIndex – 1. This method also throws StringIndexOutOfBoundsException
if the startIndex is negative or is greater than the endIndex.
1 2 3 4 5 6 7 |
StringBuffer sb = new StringBuffer("Hello world"); /* * This will delete substring from StringBuffer * from index 2, 3 and 4 */ sb.delete(2, 5); System.out.println(sb); |
Output
1 |
He world |
3. How to empty the StringBuffer (delete all characters)?
The StringBuffer class in Java does not provide any direct method using which you can empty the StringBuffer object. However, you can use the delete method and specify 0 as the start index and StringBuffer length – 1 as the end index to remove all the characters from the StringBuffer.
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("Java StringBuffer empty"); /* * This will empty the StringBuffer */ sb.delete(0, sb.length()); System.out.println("StringBuffer contains: " + sb); |
Output
1 |
StringBuffer contains: |
Please visit the StringBuilder empty or clear example to know more.
How to search substring in the StringBuffer using indexOf and lastIndexOf methods?
The indexOf
method returns the index of the specified substring within this StringBuffer object. If the substring is not found within the StringBuffer, it returns -1.
1 |
StringBuffer indexOf(String substring) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuffer sb = new StringBuffer("index of substring"); /* * This will return index 6 * because "of" starts at index 6 in the StringBuffer */ int index = sb.indexOf("of"); System.out.println(index); //this will print -1, as the StringBuffer does not contain "java" index = sb.indexOf("java"); System.out.println(index); |
Output
1 2 |
6 -1 |
The above-given method starts searching for the specified substring from index 0. If you want to search the substring from the specified start index, use an overloaded indexOf
method with the start index argument.
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuffer sb = new StringBuffer("StringBuffer indexof SubString"); /* * This will return index 0 * because "String" starts at index 0 in the StringBuffer */ int index = sb.indexOf("String"); System.out.println(index); //this will print 24, as the "String" starts at index 24 after index 1 index = sb.indexOf("String", 1); System.out.println(index); |
Output
1 2 |
0 24 |
Both of these indexOf
methods return the index of the first occurrence of the specified substring. If you want to search for the last occurrence of the substring, use lastIndexOf
method. The lastIndexOf
method searches for the substring in the backward direction (from end to start of the StringBuffer).
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("StringBuffer indexof SubString"); /* * This will return index 24 * because last "String" starts at index 24 in the StringBuffer */ int index = sb.lastIndexOf("String"); System.out.println(index); |
Output
1 |
24 |
Similarly, you can also specify the start index from where you want to search for the last occurrence using an overloaded lastIndexOf
method with the start index parameter.
How to reverse the StringBuffer?
The reverse
method replaces the StringBuffer content with the reversed content (StringBuffer reverse).
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("Java"); /* * To reverse the StringBuffer content, * use the reverse method. */ sb.reverse(); System.out.println(sb); |
Output
1 |
avaJ |
How to convert StringBuffer to String object?
The toString
method of the StringBuffer class returns a new String object containing the character sequence of this object.
1 2 3 4 5 6 7 8 |
StringBuffer sb = new StringBuffer("StringBuffer to String"); /* * To convert StringBuffer to String, * use the toString method */ String str = sb.toString(); System.out.println(str); |
Output
1 |
StringBuffer to String |
What is a StringBuffer capacity?
The StringBuffer in Java internally manages an array, also called a buffer, to store its content or character sequence. The length of this internal array is called StringBuffer capacity. The capacity of the StringBuffer is automatically increased as we add more content to it. It does it by allocating a new internal array with the required length when the existing internal buffer overflows.
Allocating a new array is a costly operation. If you know the approximate number of the character the StringBuffer object is going to hold beforehand, you should create the StringBuffer object with the required capacity using the below constructor.
1 |
public StringBuffer(int initialCapacity) |
This will avoid allocating and copying the content to the new internal array and will improve the performance of the code.
How to know the current capacity of the StringBuffer object using the capacity method?
The capacity
method returns the current capacity of the internal buffer. Its the amount of storage that is available to store the characters. If the content length to be inserted or appended to this StringBuffer object is greater than the current capacity, a new array allocation will occur to fit the new content.
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 |
StringBuffer sb = new StringBuffer(); /* * Use the capacity method of the StringBuffer * class to know the current capacity of the buffer */ //this will return 16, the default capacity for empty content System.out.println( sb.capacity() ); /* * capacity will be 16 + content length for this constructor */ StringBuffer sb1 = new StringBuffer("Hello"); //this will print 16 + 5 (i.e. length of the content) = 21 System.out.println( sb1.capacity() ); /* * If content length is more than the current * capacity, new array with larger capacity will * be allocated automatically */ sb1.append("a new array should be allocated for this content"); System.out.println(sb1.capacity()); |
Output
1 2 3 |
16 21 53 |
As you can see from the output, if we try to put content into StringBuffer having more characters than the current capacity, the capacity will be automatically increased.
How to create a StringBuffer object with a given minimum capacity?
Why do we need to ensure the capacity of the StringBuffer? Well, as we have seen in the above example, a new array needs to be allocated in case the current capacity is not large enough to fit the content. The array allocation is a costly operation involving two steps. First, the memory needs to be allocated for the new array, and second, the existing content of the buffer array needs to be copied to the newly allocated array.
We can avoid this performance penalty if we know the approximate number of characters the StringBuffer is going to hold and create the StringBuffer with the required capacity. There are two ways to do this, first using the constructor with the capacity argument which we have already seen, and second using the ensureCapacity
method to reduce it.
1 |
public void ensureCapacity(int minimumCapacity) |
The ensureCapacity
method ensures that the buffer is at least equal to the given minimum capacity. If the current capacity is less than the given minimum capacity, a new array is allocated with the capacity which is larger of the specified capacity or (old capacity * 2 ) + 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Option 1: ensure minimum capacity using constructor StringBuffer sb = new StringBuffer(50); System.out.println( sb.capacity() ); //Option 2: using the ensureCapacity method StringBuffer sb1 = new StringBuffer(); //will print default capacity i.e. 16 System.out.println(sb1.capacity()); //make it larger sb1.ensureCapacity(55); System.out.println( sb1.capacity() ); sb1.append("a new array should NOT be allocated for this content"); System.out.println( sb1.capacity() ); |
Output
1 2 3 4 |
50 16 55 55 |
How to reclaim the unused capacity using the trimToSize method?
In many cases, after some processing, we do not need the StringBuffer with a large capacity. Consider below given example.
1 2 3 4 5 6 7 8 9 10 |
StringBuffer sb = new StringBuffer(500); sb.append("This object is supposed to store a very large content"); sb.append("This object is supposed to store a very large content"); System.out.println(sb.capacity()); //empty the StringBuffer sb.delete(0, sb.length()); System.out.println(sb.capacity()); |
Output
1 2 |
500 500 |
As you can see from the output, even after emptying the StringBuffer object, the capacity of the StringBuffer object remains the same. If you do not need the extra capacity anymore, you can use the trimToSize
method.
The trimToSize
method tries to recover the storage used by the buffer. If the buffer is larger than what is required to store the current contents of the StringBuffer, this method resizes the internal array for space optimization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
StringBuffer sb = new StringBuffer(500); sb.append("This object is supposed to store a very large content"); System.out.println(sb.capacity()); //replace StringBuffer content with "hello" sb.replace(0, sb.length(), "hello"); System.out.println(sb.capacity()); /* * This will try to reduce the storage * used by an internal array */ sb.trimToSize(); System.out.println(sb.capacity()); |
Output
1 2 3 |
500 500 5 |
Below given are some of the additional Java StringBuffer examples with detailed explanations on how to use StringBuffer in Java.
Java StringBuffer Examples
- How to check if StringBuffer is empty
- How to append new line in StringBuffer content
- How to replace and replace all string in StringBuffer
- How to check if StringBuffer object contains String or substring
- How to clear contents of StringBuffer (empty or clear StringBuffer)
- How to add content at the beginning of the StringBuffer (insert at front)
- How to convert String to StringBuffer and StringBuffer to String
- How to get StringBuffer length or StringBuffer size
- How to remove the last character from StringBuffer
- How to compare two StringBuffer objects by content
- What is StringBuffer capacity
References:
Java StringBuffer class Javadoc
Please let me know if you liked the Java StringBuffer tutorial with examples in the comments section below.