View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

StringBuffer Class in Java

By Pavan Vadapalli

Updated on Dec 30, 2024 | 9 min read | 5.6k views

Share:

Basic Concept of Class in Java

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.

  • Modifiers: A class may have default access or can be public.
  • class Keyword: The keyword ‘class’ is used for class creation.
  • Class name: The name of a class should start with an initial letter that is capitalized by convention.
  • Superclass (if any): It is the name of the parent class if the class to be declared is a derived class. The name of the superclass is preceded by the ‘extend’ keyword. Any class in Java can extend only one parent. 
  • Interfaces (if any): If the class has interfaces, then a list of interfaces incorporated by the class with a comma separation between the elements of the list should be mentioned. The list is preceded by the ‘implements’ keyword. More than one interface can be implemented by a class.
  • Body: The body of a class is enclosed within the braces { }.

Check out our free technology courses to get an edge over the competition.

An Overview of String Buffer in Java

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. 

Important points about the StringBuffer class in Java

  • The Java StringBuffer is much like the String class with the features of mutability. 
  • The memory allocation and length of a string are final, whereas there are existing methods in the StringBuffer class to manipulate these string properties. 
  • Most of the methods in StringBuffer are synchronized and hence it is a thread safe class because the constituent objects cannot be fetched or utilized by several threads at the same instance of time. 
  • The abstract class AbstractStringBuilder is extended by the java.lang.StringBuffer.
  • From the superclass java.lang.Object, the String buffer inherits equals(), clone(), finalize(), hashCode(), notify(), notifyAll() and getClass() methods. 
  • The Appendable, Serializable and CharSequence interfaces are implemented by the StringBuffer. 
  • The capacity() method of the StringBuffer is used to regain the memory existing for new sequences of characters to be added. The allocation will occur beyond this.
  • Because of its time synchronization, the StringBuffer class performs slower than the StringBuilder class.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

The figure below shows the diagrammatic representation of the class The figure below shows the diagrammatic representation of the class StringBuffer in Java..

StringBuffer Constructors

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.

  1. StringBuffer()
  2. StringBuffer(int sizeOfBuffer)
  3. StringBuffer(String str)
  4. StringBuffer(charSequence []ch)

StringBuffer()

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();

StringBuffer(int sizeOfBuffer)

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);

StringBuffer(String string)

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!”);

StringBuffer(charSequence [ ]ch)

With this constructor, a StringBuffer object is created from the array of charSequence.

Methods of StringBuffer class

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. 

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

View Program
upGrad

upGrad KnowledgeHut

Full Stack Development Bootcamp - Essential

Job-Linked Program

Bootcamp

36 Weeks

View Program