Home

 › 

Articles

 › 

StringBuffer in Java: What It Is and How to Use It

hand holding a smartphone with a java logo

StringBuffer in Java: What It Is and How to Use It

Key Points

  • StringBuffer is a mutable option in Java that is faster than String.
  • The main methods for modifying a StringBuffer are append, insert, and replace.
  • StringBuffer and StringBuilder are alternatives to each other, with StringBuffer ensuring data consistency across multiple threads.

To begin, strings in Java are objects containing a set number of character values. However, the issue with them is that you can’t change the information in a string without creating a new one. So, since you need to change the data often, it can use a lot of resources. Consequently, you can use StringBuffer in Java as an alternative.

StringBuffer is a mutable option in Java that provides many of the functions of a string. Thus, it lets users store character data and change the information stored within the program. StringBuffer is also faster than String and uses fewer resources. So, it’s a useful alternative to the basic String. Let’s examine StringBuffer and learn how to use it in our code.

Key Features of StringBuffer

  • StringBuffer allows you to store character data
  • It’s a mutable function, meaning you can change the data without creating a new object
  • StringBuffer uses fewer resources because it doesn’t create a new instance every time you change the data
  • Multiple threads can access and modify StringBuffers simultaneously, and the data will be the same over all of those threads

Constructors

ConstructorWhat It Does
StringBuffer()Creates a StringBuffer with no value and an initial capacity of 16.
StringBuffer(CharSequence seq)Creates a StringBuffer containing the character sequence specified in the CharSequence.
StringBuffer(int capacity)Creates a StringBuffer with no value and an initial capacity as specified.
StringBuffer(String str)Creates a StringBuffer with the String value specified.

Methods for Modification of Strings

stringbuffer
Java has many ways to store character data in programs.

©FOTOGRIN/Shutterstock.com

Several functions in Java can modify StringBuffer data to allow you to alter the information contained in the string. Thus, you’ll need to use these operations when you want to change the details in your code. So, the main methods you’ll use to change your string are append, insert, and replace.

You can use them to alter the data contained in your string to many different data types. We’ll cover all the different ways you can work with your information. So, the following tables contain the different methods that can modify StringBuffers.

Append

MethodWhat It DoesParameters
append(boolean b)Changes the StringBuffer’s stored boolean argument to the specified sequence.b: a boolean
append(char c)Changes the StringBuffer’s stored char argument to the specified sequence.c: a character
append(char[] str)Changes the StringBuffer’s stored character array argument to the specified sequence.str: character string to append
append(char[] str, int offset, int len)Changes the StringBuffer’s representation of a section of the character array argument to the specified sequence.str: character string to append

offset: index of the int to append

len: number of characters to append
append(CharSequences s)Changes the CharSequence to the specified sequence.s: a CharSequence
append(CharSequence s, int start, int end)Changes a section of CharSequence to the specified sequence.s: a CharSequence

start: index of the first character to change

end: index of the last character to change
append(double d)Changes the StringBuffer’s stored double argument to the specified sequence.d: a double
append(float f)Changes the StringBuffer’s stored float argument to the specified sequence.f: a float
append(int i)Changes the StringBuffer’s stored int argument to the specified sequence.i: an int
append(long lng)Changes the StringBuffer’s stored long argument to the specified sequence.lng: a long
append(Object obj)Changes the StringBuffer’s stored Object argument to the specified sequence.obj: an Object
append(String str)Changes the StringBuffer’s stored String argument to the specified sequence.str: a String
append(StringBuffer sb)Changes the StringBuffer’s stored StringBuffer argument to the specified sequence.sb: a StringBuffer
appendCodePoint(int codePoint)Changes the StringBuffer’s stored CodePoint argument to the specified sequence.codePoint: a CodePoint

Insert

MethodWhat It DoesParameters
insert(int offset, boolean b)Inserts a boolean into the StringBuffer at the specified index.int offset: the index to insert the boolean at

b: a boolean
insert(int offset, char c)Inserts a character into the StringBuffer at the specified index.int offset: the index to insert the character at

c: a character
insert(int offset, char[] str)Inserts a string representation of a character array into the StringBuffer at the specified index.int offset: the index to insert the character array at

str: a String
insert(int index, char[] str, int offset, int len)Inserts a string representation of a section of the string array argument at the specified index.index: index to insert the section at

str: a string array

offset: index of len: number of characters to change
insert(int dstOffset, CharSequence s)Inserts a CharSequence into the StringBuffer.dstOffset:s: a CharSequence
insert(int dstOffset, CharSequence s, int start, int end)Inserts a section of a CharSequence into the StringBuffer.dstOffset:s: a CharSequnce

start: the index of the first character in the CharSequence to insert

end: the index of the last character in the CharSequence to be inserted
insert(int offset, double d)Inserts a double argument into the sequence at the specified index.int offset: index to insert the double at

d: a double
insert(int offset, float f)Inserts a float argument into the sequence at the specified index.int offset: index to insert the float at

f: a float
insert(int offset, int i)Inserts an int argument into the sequence at the specified index.int offset: index to insert the int ati: an int
insert(int offset, long l)Inserts a long argument into the sequence at the specified index.int offset: index to insert the long atl: a long 
insert(int offset, Object obj)Inserts an Object into the sequence at the specified index.int offset: index to insert the Object at

obj: an Object
insert(int offset, String str)Inserts a String into the sequence at the specified index.offset: index to insert the String at

str: a String

Replace

MethodWhat It DoesParameters
replace(int start, int end, String str)Replaces the characters in the specified section with the new String sequence.int start: refers to the starting index

end: refers to the ending index

str: a String

Delete

stringbuffer
Additionally, several methods interact with StringBuffers to alter the data within.

©Wright Studio/Shutterstock.com

MethodWhat It DoesParameters
delete(int start, int end)Deletes the stored characters in the substring range specified.int start: index of the first character to delete

int end: index of the last character to delete
deleteCharAt(int index)Deletes the character at the specified index.int index: index of the character to delete.

Returning Indexes

MethodWhat It DoesParameters
indexOf(String str)Returns the index of the first occurrence of the specified String argument in the StringBuffer.str: a String
indexOf(String str, int fromIndex)Returns the index of the first occurrence of the specified String argument in the StringBuffer.  str: a StringfromIndex: the index of the character to start checking from
lastIndexOf(String str)

Returns the index within the StringBuffer of the rightmost occurrence of the substring.str: a String
lastIndexOf(String str, int fromIndex)
Returns the index within the StringBuffer of the last occurrence of the substring.str: a String

fromIndex: the index of the first character to search
offsetByCodePoints(int index, int codePointOffset)Returns the index offset from the starting index as determined by the number of codePointOffset code points.index: the starting index

codePoitnOffset: the number of code points to count from the starting index

SubSequence and Substring

subSequence(int start, int end)Returns the subsequence specified.start: index of the first character to return

end: index of the last character to return
substring(int start)Returns a new String using a subsequence of characters from the current sequence starting at the index specified.start: index of the first character to return
substring(int start, int end)Returns a new String using a subsequence of characters from the current sequence within the specified index range.start: index of the first character to return

end: index of the last character to return

Set

setCharAt(int index, char ch)Sets the character at the specified index with a new character.ch: a character
setLength(int newLength)Sets the length of the StringBuffer to a new length.newLength: the new length of the StringBuffer

CodePoint

MethodWhat It DoesParameters
codePointAt(int index)Returns the character stored at the specified index.index: index of the CodePoint to return
codePointBefore(int index)Returns the character stored at the point directly before the specified index.index: index of the CodePoint before the CodePoint to be returned
codePointCount(int beginIndex, int endIndex)Returns the number of CodePoints in the specified range.beginIndex: the index of the first character

endIndex: the index of the last character
offsetByCodePoints(int index, int codePointOffset)Returns the index offset from the starting index from the number of codePointOffset code points.index: the starting index
codePoitnOffset: the number of code points to count from the starting index

Miscellaneous

MethodWhat It DoesParameters
capacity()Returns the StringBuffer’s current capacity.
charAt(int index)Returns the character stored at the specified index.index: index of the character to be returned
ensureCapacity(int minimumCapacity)Forces the capacity of the string not to be below the specified amount.minimumCapacity: minimum capacity of the StringBuffer
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters to the specified character array.srcBegin: the index of the first character to be copied


srcEnd: the index of the last character to be copied

Dst: the array to copy the characters into
dstBegin:
length()Returns the StringBuffer’s length (character count)
reverse()Replace the characters in the StringBuffer with the reverse order of the stored characters.
toString()Returns a String containing the data in the sequence.

Practical Examples

stringbuffer
To begin, StringBuffer offers a thread-safe alternative to Strings that can be altered within the code.

©ViDI Studio/Shutterstock.com

class Example1{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer("Hello ");
example.append("World");   
System.out.println(example);  
}  
}

We’ll start by creating the class “example.” Additionally, We’ve set it so that main() is publically accessible, and we can call it without creating a class instance. Then, we create a StringBuffer and set its value to “Hello .” After that, we’re going to use the append method to add “World” to the String. So, this code outputs “Hello World.”

class Example2{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer("Hello ");
example.insert(1,"World"); 
System.out.println(example);  
}  
} 

This script starts basically the same as the one before it. However, we’re going to use the insert method to add “World” at index 1 in the String. Thus, that code block outputs “HWorldello.”

class Example3{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer("Hello");
example.replace(1,3,"World");   
System.out.println(example);  
}  
}  

In this example, our StringBuffer is set to “Hello.” Then, we use the replace method to replace all characters from indexes 1 to 3 with the word “World.” So, that one outputs “HWorldlo.”

class Example4{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer("Hello World");
example.delete(1,3);//Deletes the data from index 1 to index 3
System.out.println(example);
}  
}

So, this script creates a StringBuffer that says “Hello World.” Then, we will use the delete method to delete the characters in the String from indexes 1 to 3. Thus, this one outputs “Hlo World.”

class Example5{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer("Hello World");
example.reverse();
System.out.println(example);  
}  
}

To begin, this script creates a StringBuffer with the value “Hello World.” Then, we use the reverse method on it, which does exactly what it says on the tin. So, this block outputs “dlorW olleH.”

class Example6{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer();  
System.out.println(example.capacity());  
example.append("Hello"); 
System.out.println(example.capacity()); 
example.append("Java is my favorite language");
System.out.println(example.capacity());
}  
}  

For starters, this program creates a StringBuffer with no value and a default capacity of 16. Then, we use the print function to print to output “example.capacity()” which puts it on the screen. After that, we append the String to say “World” instead.

However, this doesn’t change the capacity. Therefore, the second output will be the same. Now, the second append to “Java is my favorite language” is longer than 16 characters. When we do this, the character maximum of the String changes to (old capacity*2)+2 or (16*2)+2, so 34. So, that block outputs “16 16 34”.

class Example7{  
public static void main(String args[]){  
StringBuffer example=new StringBuffer();  
System.out.println(example.capacity());
example.append("Hello"); 
System.out.println(example.capacity());  
example.append("java is my favorite language");  
System.out.println(sb.capacity());
example.ensureCapacity(10); 
System.out.println(example.capacity());  
example.ensureCapacity(50); 
System.out.println(example.capacity());
}  
} 

To begin, this block will create a StringBuffer with no value and a default capacity of 16. Then, we’ll output that. After that, we’ll change the String data to “Hello” and output the capacity again, which hasn’t changed.

Now, we’ve changed the String to say “Java is my favorite language” and printed the new capacity of 34. After that, we’ll use the ensureCapacity to mandate that the minimum capacity is 10, which doesn’t change anything. Then we print the capacity again.

Finally, we’ve used ensureCapacity again, but, this time, we’ve set the capacity to 50 which is more than the current 34. So, the program will update the capacity again and (34*2)+2 is 70 which is more than 50. Thus, this block outputs “16 16 34 34 70”.

StringBuffer vs. StringBuilder: What’s the Difference?

However, StringBuffer is not always necessary. Consequently, StringBuilder is a drop-in alternative for StringBuffer. Still, they differ mostly in whether the data will remain the same over multiple threads. StringBuffer ensures the data will remain the same when multiple threads use the String, while StringBuilder does not. Therefore, you can use StringBuilder when only one thread at a time uses the information. 

Most of the time, only one thread uses a string at any given time. So, you should use StringBuilder instead of StringBuffer wherever possible. However, if you know multiple threads will access a String, you should use StringBuffer.

Frequently Asked Questions

What is StringBuffer in Java?

StringBuffer is a function in Java that creates and stores a mutable sequence of characters.

What is a String in Java?

A String is a sequence of characters stored as a class of java.lang.

What are the limitations of Strings in Java?

Strings are immutable objects in Java, meaning they cannot be changed once stored. 

How does StringBuffer differ from Strings in Java?

StringBuffer is a mutable object, meaning you can change it within the code. Since you can change the data after creation, you don’t need to create a new instance of the string every time you change it. This feature makes them more resource-efficient than Strings.

What is StringBuilder in Java?

StringBuilder is a replacement for StringBuffer.

How does StringBuilder differ from StringBuffer in Java?

StringBuilder does not guarantee data synchronization when the string is accessed by multiple threads at once. Thus, StringBuffer is a thread-safe function while StringBuilder is not. 

We recommend using StringBuilder when the string is not accessed by multiple threads, as it is faster than StringBuffer.

How do I modify a StringBuffer in Java?

You can modify a StringBuffer in Java using the append, insert, and replace methods. Append takes many data types, including int, char, and Strings. When you use the append method, the new data will be added to the end of the stored string.

Insert requires you to specify an index where you want the data added. Then, it will put the new characters into the sequence where you stated. The insert method also takes many data types.

Replace has you specify a range of indexes you want replaced with the new data value. It takes many data types.

What are the constructors of StringBuffer in Java?

The constructors of StringBuffer are StringBuffer(), StringBuffer(CharSequence seq), StringBuffer(int capacity), and StringBuffer(String str).

To top