StringBuffer Class in Java
Updated on Dec 30, 2024 | 9 min read | 5.6k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 30, 2024 | 9 min read | 5.6k views
Share:
The basic concepts of any object-oriented programming language are the classes and objects which spin around various practical and real-life entities. A class in Java is a user-defined template or prototype or blueprint from which the objects are developed. It denotes the set of methods or properties that are common to all objects of the same data type. The declaration of a class includes the below-mentioned components in the same order.
Check out our free technology courses to get an edge over the competition.
The StringBuffer in Java is a class used to generate changeable objects of String type. A StringBuffer can be incorporated to reverse, append, concatenate, replace and manipulate a sequence of characters or strings. Respective methods of the StringBuffer class are created to accomplish these functions in a Java program. The strings in Java are non-editable and hence are referred to as immutable types. It can be changed only by overwriting an existing string. StringBuffer can store the character sequences while it can enable the mutation of the string.
The StringBuffer class in Java features the flexibility of memory allocation of the character sequence. This implies that a string can be modified with the help of the StringBuffer class. The contingent memory reserved for future modification that exists in the StringBuffer class is the principal element of this modification.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
The figure below shows the diagrammatic representation of the class The figure below shows the diagrammatic representation of the class StringBuffer in Java..
As mentioned earlier, the StringBuffer class is used to generate mutable sequences of characters or objects of string type. In other words, the string can be altered even after it is completely created. This denotes a writable and growable character sequence. So, when a programmer has the need of making frequent modifications in the input string, it is recommended that the StringBuffer class is used. The StringBuffer class defines four different constructors discussed below.
This constructor is used to create a StringBuffer with empty or null content. It has sixteen reserved spaces for the characters by default.
Example: StringBuffer sb = new StringBuffer();
This constructor creates an empty string and accepts an integer argument that specifies the size of the newly created empty buffer.
Example: StringBuffer sb = new StringBuffer(20);
This constructor creates a StringBuffer that accepts an input argument of string type as the initial buffer content. There exists a pre-allocated set of 16 contingent memory locations for the modification of input string if required. This pre-allocated space does not include the buffer memory spaces.
Example: StringBuffer sb = new StringBuffer(“Hello World!”);
With this constructor, a StringBuffer object is created from the array of charSequence.
The StringBuffer class contains several methods that are discussed in this section with examples.
length():
This method returns the length of the object in the StringBuffer class.
capacity():
This method is invoked to return the capacity of the object in the StringBuffer class.
The output of the above code is as follows:
append():
This method is invoked to affix the specified parameter representing a string at the end of the existing StringBuffer. We overload this method for all the primitive objects and data types.
The output of the above code is as follows:
Hello World 2017
insert():
This method accepts two input parameters –a value to be inserted and an integer value representing the index at which the value is to be inserted in the string. The index specifies the StringBuffer where to add the input parameter of the character sequence. We overload this method to handle primitive objects and data types.
The output of the above code is as follows.
Hello World 2017
reverse():
This function enables the buffer to reverse the existing string or the contents of the character sequence in the buffer. The reversed string is returned. If the object does not contain an existing string or a character sequence, the reverse() function throws a NullPointerException.
The output of the above code is mentioned below:
dlroW olleH
delete(int startIndex, int endIndex)
This method takes two input arguments. The first parameter serves as the index of the start of the deletion and the second one denotes the index of the end of the deletion. Both the input parameters are integer values. Therefore, the sequence of characters between the start and end index is deleted. The function returns the remaining content of the string buffer.
deleteCharAt(int index)
This function is used to delete a single character from the contents of the string buffer. It takes a single input parameter of integer type. The integer value determines the index of the value to be deleted from the character sequence in the buffer. This method returns the remaining content after deletion of the single character from the existing contents of the buffer.
replace(int startIndex, int endIndex, String str)
It is used to replace the specified portion of a character sequence with another string. This method in the StringBuffer class accepts three input parameters. The first two parameters are of integer type and denote the start and end index of the existing string buffer contents to be replaced. The third input parameter is string type. This is the character sequence that replaces the character sequence in the existing string buffer contents from the specified start index.
ensureCapacity()
This method can be used to assure the least capacity of the object in the StringBuffer class. If the input argument of this method is less than the allocated memory’s existing capacity, then no change will happen in the existing capacity. However, if the input parameter is more than the existing allocated memory’s capacity, the current capacity of the allocated memory is altered, as mentioned below.
newCapacity = (oldCapacity*2) + 2
Differences between String and StringBuffer in Java
StringBuffer | String |
This class is a mutable class in Java. | The String class is non-changeable or immutable. |
Its execution is faster and less memory is consumed when strings are concatenated. | Its operation is slow and more memory is consumed when many strings are concatenated. |
The StringBuffer class does not override the equals( ) method of the object class. | The equals() method of the object class is overridden by the String class. So, the comparison of two strings can be performed using the equals() functions. |
At upGrad, we understand the importance of practical, hands-on learning – especially when it comes to software development. As a result, our courses and training initiatives have practicality at their very core. One such initiative is Full Stack Development Bootcamp which will help you develop all the relevant skills required to excel in full-stack development.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources