Class StringBuffer in Java: StringBuffer is a associate class of String which provides majority of functionality of strings.
As you know String for its immutable character sequences and fixed-length.
In contrast, StringBuffer speaks for its growable and writeable character sequences.
StringBuffer might have substrings and characters appended at the end or inserted in the middle.
Moreover StringBuffer will grow automatically for additions and often it has more characters preallocated than the actual need.
Both String and StringBuffer used more often in Java, but many developers most deal only with String and let Java to manipulate StringBuffer’s in background by using the overloaded + operator.
Introduction to StringBuffer
String objects are constant strings, whereas StringBuffer objects are modifiable strings.
ava distinguishes constant strings from modifiable strings for optimization purposes.
In particular, Java performs specific optimizations including String objects (like sharing one String object across multiple references) because it knows there will be no change in objects.
when given the choice between using a String object to represent a string versus a StringBuffer object to represent that string, always prefer a String object if the string will not change; this improves performance for sure.
StringBuffer Constructors
Class StringBuffer provides four types of constuctors through which it will be initialized.
Default Constructor:
StringBuffer buffer = new StringBuffer()
Above constructor is the default StringBuffer constuctor to create a StringBuffer with no characters in it and an intitial capacity of 16 characters (default for a StringBuffer).
Integer Argument Constructor:
Syntax:StringBuffer buffer = new StringBuffer(int size);
Example:
StringBuffer buffer = new StringBuffer(20);
Above type of constuctor takes an integer argument to create a StringBuffer with no characters in it and the intitial capacity specified by the integer argument.
String Argument Constructor:
Syntax:StringBuffer buffer = new StringBuffer(String str);
Example:
StringBuffer buffer = new StringBuffer("TracedDynamics");
Above variation of constructor takes a String argument (i.e, in this example case a string literal) to create a StringBuffer containing the characters in the String argument.
The inital capacity is the number of charcters in the string argument plus 16.
CharacterSequence Argument Constructor:
Syntax:StringBuffer buffer = new StringBuffer(CharSequence chars);
Above constructor creates an object that contains the character sequence contained in chars.
You May Also Like,
StringBuffer Methods
Following are the different methods provided by the StringBuffer.
length()
The current length of a StringBuffer can be found via using the length() method.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer Length: "+buffer.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Length: 13
capacity()
This method provides the total allocated capacity through the capacity() method.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer Capacity: "+buffer.capacity());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Capacity: 29
So whats the logic behind capacity output value of 29 in above program ? Since StringBuffer by default allocates space for 16 additional characters, total length of input string plus 16 will be the capacity.
In this the input string length is 13 and StringBuffer default allcoation is 16, so 13+16 = 29 is the capacity.
ensureCapacity()
If you are looking to preallocate space for a specific number of characters after a StringBuffer has been constructed, we can use ensureCapacity() method to set the size of the buffer.
This way of implementation is useful if you know in prior that you will be appending a huge number of small strings to a StringBuffer.
Syntax:
ensureCapacity(int capacity)
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer();
System.out.println("Before Setting ensureCapacity : " +buffer.capacity());
buffer.ensureCapacity(20);
System.out.println("After Setting ensureCapacity : " +buffer.capacity());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Before Setting ensureCapacity : 16
After Setting ensureCapacity : 34
setLength()
Using setLength() method, we can set the length of the string within a StringBuffer object.
Syntax:
setLength(int length)
Note that, the length value should be non negative.
When you increase the size of a string, the null characters are added to the end. If you call setLength() with a value less than the current valu returned by length() method, then the characters stored above the new length will be lost.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("Before Setting Length : " +buffer.length());
buffer.setLength(20);
System.out.println("After Setting Length : " +buffer.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Before Setting ensureCapacity : 16
After Setting ensureCapacity : 34
charAt()
Using charAt() method, we can obtain the value of a single character from a StringBuffer.
Syntax:
charAt(int index).
Note that, the index value should be non negative.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("Char at: " +buffer.charAt(2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Char at: a
setCharAt()
Using setCharAt() method, we can set the value of a character from a StringBuffer.
Syntax:
setCharAt(int index, char ch)
Note that, the index value should be non negative.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
buffer.setCharAt(2, '$');
System.out.println("Set Char at: "+buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Set Char at: Tr$ceDynamics
getChars()
Using getChars() method, we can copy a substring of a StringBuffer into array.
Syntax:
getChars(int startIndex, int endIndex, char target[], int targetStartIndex)
Here the startIndex specifies the index of the beginning of the substring, and endIndex specifies a index that is one past the end of desired substring.
This means that the substring contains the characters from startIndex through endIndex-1. The array that wil receive the characters is specified by target.
The index within target at which the substring will be copied is passed in targetStartIndex.
We have to assure that the target[] is big enough to hold the number of characters in the specified substring.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("Trace Dynamics");
char[] array = new char[] { 'w', 'e', 'l', 'c', 'o', 'm', 'e' };
buffer.getChars(6, 9, array, 3);
System.out.println(array);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
welDyne
append()
Basically the method append() concatenates the representation string of any other type of data to the end of the triggering StringBuffer object.
Inorder to obtain string representation for each parameter, String.valueOf() method is called.
Also append() method has numerous overload versions, here are they.
- append(String str)
- append(boolean b)
- append(int i)
- append(Object obj)
- append(char c)
- append(char[] str)
- append(CharSequence s)
- append(float f)
- append(double d)
- append(long lng)
- append(StringBuffer sb)
- append(CharSequence s, int start, int end)
- append(char[] str, int offset, int len)
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("Trace Dynamics");
System.out.println("before inserting: " + buffer);
buffer.insert(14, " Welcomes You");
System.out.println("After inserting: " + buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
before appending: TraceDynamics
After appending: TraceDynamics Welcomes You
insert()
The method insert() inserts one string into another.
This method is overloaded to accept the values of all the types, Objects, Strings and CharSequences.
Likewise append() method, insert() also String.valueOf() to obtain the string representation of the value it is called with.
String.valueOf() method called to obtain a string representation for each parameter.
Here are the different forms of insert() methods.
- insert(int index, String str)
- insert(int index, char ch)
- insert(int index, Object obj)
In above, index specifies at which point the string will be inserted into the invoking StringBuffer object.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("Trace Dynamics");
System.out.println("before inserting: " + buffer);
buffer.insert(14, " Welcomes You");
System.out.println("After inserting: " + buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
before inserting: Trace Dynamics
After inserting: Trace Dynamics Welcomes You
reverse()
The method reverse() is used to reverse the characters with in a StringBuffer object.
Syntax:reverse()
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer Reverse: " + buffer.reverse());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Reverse: scimanyDecarT
delete()
The method delete() is used to delete the characters with in a StringBuffer object.
Syntax:
delete(int indexStart, String indexEnd)
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer Delete: " + buffer.delete(0,5));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Delete: Dynamics
deleteCharAt()
The method delete() is used to delete the characters at a specified index.
Syntax:
deleteCharAt(int index)
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer DeletCharAt: " + buffer.deleteCharAt(0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Delete: Dynamics
replace()
The method replace() is used to replace the characters at a specified index.
Syntax:
replace(int indexStart, String indexEnd, String str)
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer Delete: " + buffer.replace(0,5,"Test"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer Delete: TestDynamics
substring()
The method substring() is used to retrieve a portion of a string at a specified index.
Syntax:
substring(int indexStart)
substring(int indexStart, String indexEnd)
The second syntax above returns the substring which starts at indexStart and process through indexEnd-1.
Here is the code example which utilizes second syntax above.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
System.out.println("StringBuffer substring: " + buffer.substring(0,5));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer substring: Trace
Why StringBuffer is Mutable?
As per builtin behaviour String class in Java is Immutable, which means whenever we declare a String variable we cannot modify the data or perform any manipulations.
For some specific instances we might have to modify the data of a String, for such scenarios we can leverage StringBuffer which is mutable(modifiable) by nature.
substring(int indexStart)
substring(int indexStart, String indexEnd)
Convert StringBuffer to String
Converting StringBuffer to String is a straight forward task, we just have to leverage toString() method.
Applying toString() method on StringBuffer object will serve the purpose.
Here is the example.
public class Main {
public static void main(String[] args) {
try {
StringBuffer buffer = new StringBuffer("TraceDynamics");
String output = buffer.toString();
System.out.println("StringBuffer to String: " +output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
StringBuffer to String: TraceDynamics
Note:
In JDK 1.5 version, Java introduced StringBuilder for handling string capabilities.
This is very much similar to StringBuffer apart from one one important difference, StringBuilder is not synchorized(not thread safe).
Faster Performance is great advantage of StringBuilder.
To conclude this java tutorial, we covered various constructors, methods of class StringBuffer in Java.
Frequently Asked Questions
What is StringBuffer in Java?
StringBuffer is a mutable sequence of characters used for creating and manipulating string data efficiently.
How does StringBuffer differ from String in Java?
Unlike String, which is immutable, StringBuffer allows modification of its contents without creating new instances.
When should I use StringBuffer over StringBuilder?
Use StringBuffer when thread safety is required, as it is synchronized, unlike StringBuilder.
Can StringBuffer be converted to a String?
Yes, using the toString() method of StringBuffer converts it to a String.
How do you append data to a StringBuffer?
Use the append() method to add data at the end of the StringBuffer.
Is StringBuffer efficient for concatenating strings in a loop?
Yes, it’s more efficient than using + operator with Strings, especially in loops.
How can I insert a string into a StringBuffer?
Use the insert() method to add a string at a specified index in the StringBuffer.
Can I reverse a string using StringBuffer?
Yes, the reverse() method in StringBuffer reverses the sequence of characters.
What methods are used to delete or remove characters in StringBuffer?
Use delete() or deleteCharAt() methods to remove characters or a sequence of characters.
How do I ensure the capacity of a StringBuffer?
Use ensureCapacity() to ensure that the buffer has at least a specified minimum capacity.