StringBuffer Class in Java
Overview
The StringBuffer class is used for storing the mutable sequence of different datatypes which means we can update the sequence of the StringBuffer class very easily and efficiently without creating a new sequence in memory.
StringBuffer is faster than the String class and provides various additional methods for deleting the sequence elements, updating the sequence elements, etc. The memory allocation of the StringBuffer object is done in the heap section of memory.
What is StringBuffer in Java?
Consider a word "HelloWorld" which is stored as a String variable, and you want to add several characters in this word, but when you start adding characters to the String, every time a new memory is allocated for the updated String, no updation takes place in the original String.
This causes a lot of memory wastage, but when we store the String in the StringBuffer class, no new memory is allocated (StringBuffer objects are like String class objects, but they can be modified to perform manipulating operations on the StringBuffer). ''This property of the StringBuffer class in Java is called “mutable”
Let's understand this property using an image.
In the above image, we can see clearly that new memory is allocated in the case of String after adding the new String to the existing String.
Example:
On the other hand, adding the String in the existing StringBuffer sequence using the append() method (we will study all the methods of the StringBuffer class in Java later in this article) will not allocate new memory for storing new sequences. We can see this clearly in the picture.
So, this is one of the reasons the StringBuffer class is mostly used when we have to deal with different kinds of operations on the String. Also, the StringBuffer object is thread-safe, which means multiple threads cannot be able to access the object of StringBuffer in java.
In simple words, we cannot perform multiple operations simultaneously. Let's discuss the Syntax of the StringBuffer in java.
Syntax of StringBuffer class
StringBuffer class extends the two interfaces CharSequence and Serializable and one class i.e Object class. Although an Object class is extended by all the user-defined class and the in-built class by default in the java.
Syntax:
Class Declaration
StringBuffer is declared as all the classes in the java declare using the new keyword. Also StringBuffer class is not a primitive class, that's why we cannot directly assign the particular value to the StringBuffer object like StringBuffer m = value; this is the invalid declaration of the StringBuffer object.
Syntax:
The object name is the reference of the StringBuffer class by which we can access the many in-built methods of the StringBuffer class in Java.
Example of Creating a StringBuffer Object
Example:
StringBuffer class provides various types of constructors for different operations.
Let's discuss the constructors of the StringBuffer class.
Important Constructors of StringBuffer class in Java
StringBuffer in java provides different types of constructors that help for converting the ordinary String characters to StringBuffer format and helps to configure some properties of StringBuffer such as size, etc.
Let's discuss different Constructors of StringBuffer in java one by one:
- StringBuffer(): This constructor is used for creating a StringBuffer with no characters and the initial capacity is 16 bytes. Capacity is defined as the maximum elements that the StringBuffer object can store. (we will study the capacity of the StringBuffer object later in this article.) This constructor doesn't require any parameter.
Syntax:
- StringBuffer(int capacity): This constructor is used for initializing the initial size of the StringBuffer. This constructor takes one parameter the capacity of the StringBuffer.
Syntax:
- StringBuffer(String): This constructor accepts the String as a parameter and converts the String to the StringBuffer object. The default capacity of the StringBuffer is 16 bytes.
Note:
If the capacity of StringBuffer gets full after adding an extra String, the new capacity of StringBuffer will be
Syntax:
- StringBuilder(char sequence):: This constructor is used for creating a StringBuilder of charsequence.The charsequence is the sequence of the characters.
The default capacity of the StringBuffer is 16 bytes. If the capacity of StringBuffer gets full after adding an extra char sequence, the new capacity of StringBuffer will be .
Syntax:
Methods of Inherited and StringBuffer Class in Java
StringBuffer in java provides various types of inbuilt methods that help to perform different operations on StringBuffer. Let's discuss each method one by one.
append() method:
This method is used for appending the new sequence to the existing sequence of the StringBuffer class in Java.
Syntax:
StringBuffer.append(datatype): The append(datatype) method of the StringBuffer class is used for appending the element of a particular datatype at the end of the current sequence of the StringBuffer.
Note:
If we append the particular value in the empty StringBuffer sequence, It will not cause any error.
Parameter: This method takes one parameter, that is, any datatype value that needs to be appended in the StringBuffer sequence.
ReturnType: This method returns the reference of the StringBuffer object.
Let's understand the method of StringBuffer in java
In the above program, we are appending different kinds of datatype values to the sequence of StringBuffer. In the above case, we are appending the int and String datatypes values to the StringBuffer sequence.
Output:
appendCodePoint():
This method is used for appending the String representation of the Unicode characters to the sequence of the StringBuffer. For example, the Unicode value of character 'A' is 67.
This Unicode value is converted to the String "A"` and then appended to the sequence of the StringBuffer class.
Syntax:
StringBuffer appendCodePoint(int value): This method takes the Unicode value and adds the String representation of the Unicode at the end of the sequence of StringBuffer.
The value must be greater than equal to zero. If the value is negative, it will cause an error, i.e. IllegalArgumentException because the Unicode value is always non-negative.
Parameter: This method takes one value, the Unicode value, as a parameter.
Return type: This method returns the object reference of the StringBuffer class.
Let's understand the method of StringBuffer in java
Output:
In the above snippet, we are adding the Unicode value of 'a' to the StringBuffer sequence and the resultant sequence is Helloa.
capacity() method:
This method is used for finding the initial capacity of the StringBuffer object. The default capacity of the StringBuffer class is 16 bytes.
Syntax:
int capacity(): This method returns the capacity of the StringBuffer object. The default capacity of the StringBuffer is 16 bytes.
When the capacity of StringBuffer gets full, the new capacity of StringBuffer will be $(previousCapacity+1)*2$.
Return type: This method returns the current capacity in int format.
Let's understand the method of StringBuffer in java
Output:
In the above snippet, the capacity of the StringBuffer sequence increases when the capacity gets full.
The default capacity is 16, and the new capacity is (16+1)*2 i.e., 34.
charAt() method:
char charAt(index):
This method is used for getting character values present at the index of the StringBuffer sequence.
Parameter: This method takes one parameter the index of the character. The range of the index must be in the range [0, SizeofStringBuilder-1].
if the value of the index is outside the range, this causes an IndexOutOfException, and program will be stopped.
Return type: This method returns the character present at the index value in the StringBuffer sequence.
Let's understand the method of StringBuffer in java
Output:
The above snippet is printing the character that is present at index 0, and the second printing line is causing an error due to the invalid range of index value.
deleteCharAt() method:
This method is used for deleting the particular character at the given index from the StringBuffer sequence.
Syntax:
StringBuffer.deleteCharAt(index): This method is used to delete a particular character present at the index in the StringBuffer sequence. The value of the index must be in the range .
If the value of the index lies outside the range. It will cause an error i.e indexoutofException.
Parameter: This method takes one parameter, which is the index of the character.
Return type: This method's return type is StringBuffer reference.
Let's understand the method of StringBuffer in java
Output:
The above snippet is used for deleting the character at index 2 of StringBuffer Scaler.
setCharAt() method:
This method is used for inserting the character at the particular index of the StringBuffer sequence.
Syntax:
void setCharAt(index, char c): This method is used for inserting the character at the particular index in the StringBuffer sequence.
The range of index should be in [0-lengthofsequence]. If the value of the index lies outside the range. It will cause an error i.e. indexoutofException.
Parameter: This method takes two parameters; one is the index value, and the second parameter is the character that is inserted at the index position in the StringBuffer sequence.
if the value of the index is outside the range, this causes an indexoutofException and the program will be stopped.
Return type: The return type of this method is void.
Example:
Let's understand the method of StringBuffer in java
Output:
The first printing line will print the updated sequence of the StringBuffer, but the second printing line will cause an error due to the invalid range of the index in the parameter of the method.
reverse() method:
This method is used for reversing the StringBuffer sequence.
This is in place reverse of the sequence, meaning no extra memory is used during the StringBuffer sequence's reverse.
Syntax:
StringBuffer.reverse(): This method is used to reverse the StringBuffer sequence.
Parameter: This method doesn't take any parameters.
Return type: This method return StringBuffer reference.
Let's understand the method of StringBuffer in java
Output:
The above snippet reverses the StringBuffer sequence i.e Scaler to relcaS.
length() method:
This method is used for finding the length of the StringBuffer sequence. Length is the number of elements of the StringBuffer sequence.
Syntax:
StringBuffer.length(): This method is used for calculating the length of the StringBuffer sequence. We will also learn the difference between the capacity and length of the StringBuffer object later in this article.
Parameter: This method doesn't take any parameters.
Return type: This method returns the length of the StringBuffer sequence.
Let's understand the method of StringBuffer in java
The above snippet prints the length of the StringBuffer sequence i.e., 6 is the length of the sequence in the above snippet.
indexof() method:
This method is used for finding the first index of the given String in the sequence of the StringBuffer.If the String is not present in the sequence of the StringBuffer this method will return -1.
Syntax:
int indexof(String): This method returns the first index of the given String in the sequence if it is present; otherwise, this method returns -1, which indicates String is not present in the StringBuffer sequence.
Parameter: This method takes one parameter i.e, String.
Return type: This method returns the first index value of String if present; otherwise returns -1.
Let's understand the method of StringBuffer in java
Output:
In the above snippet, the "S" String occurs at the first index of the StringBuffer sequence; that's why we get 0 in the first printing statement, but in the second printing line, we get -1 because the "z" String is not present in the sequence of StringBuffer.
lastIndexof() method:
This method is used to find the last index of the particular StringBuffer sequence.
If the sequence is not present in the StringBuffer sequence. This method returns -1, otherwise will return the starting index value of the sequence.
Syntax:
int last index of(String): This method returns the last index of the given String in the sequence of the StringBuffer.
Parameter: This method takes one parameter, i.e., String.
Return type: This method returns the last index of the String if it is present in the Sequence of StringBuffer; otherwise returns -1.
Let's understand the method of StringBuffer in java
Output:
In the above snippet, the first printing line will return the last index of String(Scaler) present at last, so 6 is returned. But in the second printing line "z" String is not present in the sequence of the StringBuffer, that's why -1 is printed.
isEmpty() method:
This method is used to check whether the StringBuffer object contains any sequence or not.
Syntax:
StringBuffer.isEmpty(): If the StringBuffer sequence is empty, this method will return true or false. When the StringBuffer sequence is not empty.
Parameter: This method doesn't take any parameters.
Return type: The return type of this method is boolean, i.e., either true or false.
Let's understand the method of StringBuffer in java
Output:
The true value is returned because, at the start, the StringBuffer is empty but appending the text to the StringBuffer contains some sequence that why false is returned.
substring() method:
This method is used for getting the substring from the StringBuffer sequence. This is one of the important methods of StringBuffer in java.
Syntax:
StringBuffer.substring(start index,endingindex+1): This method takes two parameters to the start index of the sequence and the ending index of the sequence.
The starting index must be greater than 0 and smaller and equal to the ending index.
Parameter: This method takes two parameters i.e. Starting index and the ending index of the sequence.
Return type: The return type of this method is String.
Consider the below image for a better understanding of the substring() method in the StringBuffer. The text is the StringBuffer object with the help of this object we are finding the substring of the StringBuffer sequence.
The text.substring(3,6) will convert the sequence from index 3 to 5 (i.e., gra) in the String format "gra" and returns.
Let's understand the method of StringBuffer in java
Output:
The string "sh" is returned because we want substring starting from index 4, and "yus" is returned because the index of y is two and the ending index is 4. That's why we get substring "yus".
delete() method:
This method is used for deleting the whole sequence from the buffer or particular sequence of the StringBuffer. This method takes two parameters, the starting index of the sequence and endingindex of the sequence that need to be deleted from the buffer.
Syntax:
StringBuffer.delete(startindex,endingindex+1)
Parameter: This method takes two parameters. The starting index must be greater than equal to 0 and smaller than equal to the ending index.
Return type: This method returns the StringBuffer reference.
Let's understand the method of StringBuffer in java
Output:
The sequence Aayu is returned because we have deleted the sequence starting from index 4 i.e sh and in the next deletion, we delete the sequence starting from index 2 and ending index 5(an empty sequence) that's why Aa is returned.
These are some methods of the StringBuffer class in Java.
Inherited Methods of StringBuffer in Java
Let's discuss some inherited methods in the StringBuffer class. StringBuffer inherits the object class, and also Object class is the parent class of all the classes in the java language.
hashCode() method:
This method is used for generating the hash value of a particular object of the StringBuffer class.
- The hashCode() method used inbuilt to calculate the hash value of a particular class's object. This hash value is used for the comparison of two objects of the StringBuffer class.
In the above image, the hash value of the StringBuffer sequence is calculated using the hashCode() method.
Syntax:
- StringBuffer.hashCode(): This method is used to return the hash value of the StringBuffer object.
Parameter: This method doesn't take any parameters.
Return type: This method returns the hash value in int format.
Let's understand the method of StringBuffer in java
Output:
In the above snippet, the hashCode of the StringBuffer object is returned, which helps in many operations like comparing two objects.
equals() method:
This method is used to compare two objects of the StringBuffer class in Java. Internally equals() method use the hashCode() method for comparison of two objects.
If the hash code values of two objects are equal, then this method returns true otherwise returns false.
Note:
The hash value of every StringBuffer object is unique. Even if they contain equal sequences.
Syntax:
StringBuffer.equals() method: This method is used for the comparison of two StringBuffer objects. Two objects are equal when only the hash value of two objects is the same.
Parameter: This method takes one parameter, that is, an object of a particular class.
Return type: This method returns the boolean value, either true or false.
Let's understand the method of StringBuffer in java
Output:
The output is false because the hash values of both objects are different due to the different references.
getClass() method:
This method is used for getting the exact path of the class present in the jdk which is the runtime class of the object.
Syntax:
- StringBuffer.getClass(): This method returns the class path in the JDK.
Parameter: This method doesn't take any parameters.
Return type: This method returns the path of the class in the String format.
Let's understand the method of StringBuffer in java
Output:
This is the path of the StringBuffer class in the JDK.
toString():
This method is used for String representation of the StringBuffer object. This method internally converts the StringBuffer sequence into String format and returns.
Syntax:
StringBuffer.toString(): This method is used for the String representation of the StringBuffer object.
Parameter: This method doesn't take any parameters.
Return type: The return type of this is String.
Let's understand the method of StringBuffer in java
Output:
Scaler is the String representation of StringBuffer object that is m. Use this Java Compiler to compile your code.
Two Important Method capacity() and length().
StringBuffer in java contains two methods that are capacity() and length(). Although these methods look similar, they are totally different. Let's understand the internal working of both methods.
StringBuffer.Capacity(): This method indicates the maximum number of elements the StringBuffer object can hold. When the StringBuffer capacity gets full.
Internally StringBuffer updates the capacity by . By default 16 bytes is the capacity of the StringBuffer when StringBuffer contains no elements.
In the above image, the capacity of the StringBuffer is 16 bytes, but the current sequence length is 9 bytes.
StringBuffer.length(): The method tells us the length of the current StringBuffer sequence which means the number of characters of the StringBuffer sequence.
The length of the StringBuffer is always smaller and equal to the capacity of the StringBuffer capacity.
The capacity() method has already discussed in the above section of the article. In the above picture, the number of characters of StringBuffer sequence is 9 that’s why the length is 8.
Java Program to Clear the StringBuffer
We can clear the StringBuffer by performing the following ways.
Example 1: Java program to clear StringBuffer using delete()
We can use the StringBuffer.delete() method for clearing/deleting the sequence of the StringBuffer.
The syntax and working of this method has already discussed in the above section of the article.
Let's understand the method of StringBuffer in java
Output:
In the above program, we cleared the StringBuffer object using the delete() method of the StringBuffer class.
Example: Clear the StringBuffer using setLength().
We can clear the StringBuffer sequence by setting the length of the StringBuffer to 0 using the setLength() method of the StringBuffer class. Let's understand this using an example.
Let's understand the method of StringBuffer in java
Output:
Initially StringBuffer object contains a sequence that is Aayush, but after setting the length of the StringBuffer to zero, the sequence from the StringBuffer is cleared. That's why at last empty sequence is returned.
- Clear the StringBuffer by creating a new object
We can also clear the StringBuffer sequence by reinitializing the object of the StringBuffer class that already contains a particular sequence.
Because after reinitializing the object of StringBuffer a new memory is allocated for storing the sequence, and older memory gets destroyed.
Output:
Initially, the StringBuffer object contains a particular sequence, but after reinitializing the object of the StringBuffer the sequence is cleared from the StringBuffer object. That's why the empty sequence is returned.
Conclusion
- StringBuffer in java is used for storing mutable sequences that increase their efficiency.
- The object of StringBuffer in java is thread safe multiple threads cannot access the StringBuffer particular object simultaneously.
- StringBuffer is fastest than the String class due to the mutable property of the StringBuffer class.
- The default capacity of the StringBuffer in java is 16 bytes.
- StringBuffer is mostly used when we perform several dynamic addition operations. We cannot use the String class because it will cause a lot of memory waste due to the immutable property of the String class.