StringBuffer Class in Java | Example Program

StringBuffer in Java is a peer class of String that provides much of the functionality of strings. It provides more flexibility than String.

As we know that a string is fixed-length, immutable, and cannot be modified. That is, once we create a String object, we cannot change its content.

To overcome this, Java language introduced another class called StringBuffer.

Java StringBuffer represents a growable nature and mutable. That means that once we create a StringBuffer class object, we can perform any required changes in the object. i.e, its data can be modified.

That’s why StringBuffer class objects are mutable in Java. It creates strings of flexible length that can be modified in terms of both length and content. That’s why StringBuffer is more flexible than String.

The methods of string buffer class can directly manipulate data inside the object. We can easily insert characters and substrings in the middle of the string or add another string to the end. StringBuffer can automatically expand to create room for such additions.

StringBuffer class method is synchronized. Therefore, it is a thread-safe class but it is slower than string.

Java StringBuffer class declaration


StringBuffer class extends Object class and implements Serializable, Appendable, and CharSequence interfaces. The general syntax to declare StringBuffer class in Java is as follows:

public final class StringBuffer
   extends Object
      implements Serializable, CharSequence

StringBuffer class is present in java.lang package similar to the string class.

Difference between Length and Capacity in Java StringBuffer


Consider the below figure.

Difference between length and capacity in Java StringBuffer class

In Fig 1, we have created a string object with the content “Hello”. We have already studied in the String chapter that once we create a string object with content, there is no chance to change its content because the string object is immutable.


That means if we cannot change its content, the length of content “Hello” is fixed i.e. 5 and its capacity is also 5 because we cannot add new characters.

Therefore, in the string, the terminology length and capacity both are the same. Therefore, string never uses the terminology “capacity“.

But in the case of StringBuffer, there is a small difference between length and capacity.

Capacity: The total number of characters hold in the StringBuffer object is called capacity.

Length: The number of characters already present in the StringBuffer object is called length.

In Fig 2, we have created a StringBuffer object with the same content. In the case of StringBuffer, the length of the content “Hello” is also 5.

But is it possible to add some more characters to the existing object or not?

Yes, we can also add characters in the existing object because the capacity of StringBuffer is not full. Here, the capacity is not 5.

Let’s understand this concept with the help of a realtime example.


Realtime Example:

Assume that there is a classroom. In the classroom, the capacity of classroom is 100. That is the total number of students who can sit in the classroom is 100.

But currently, only 20 students are there. So, many seats are vacant. If the classroom is considered as StringBuffer, length is 20 and capacity is 100. We can add 80 more students to the classroom. That means we can add 80 characters more in the existing object.

Hope you will have understood the difference between length and capacity clearly in the case of StringBuffer.

Constructors of StringBuffer class in Java


StringBuffer class defines four constructors in Java. They are as follows:

1. StringBuffer(): This constructor creates an empty string buffer object with an initial capacity of 16 characters.

2. StringBuffer(int size): This constructor creates an empty string buffer object and accepts an integer value that specifies the size or length of the string object.

3. StringBuffer(String str): This constructor creates a string buffer object with the specified string whose size is equal to the string specified in this constructor.

4. StringBuffer(CharSequence seq): This form of constructor creates a string buffer that contains the same characters as the specified CharSequence.

How to create StringBuffer Objects in Java


There are mainly three ways to create StringBuffer objects in Java. Let’s understand them one by one.

First way:

The first way for creating a StringBuffer object is that first allocate the memory for the StringBuffer object by using the new operator and then store the string into it.


The general syntax to create a string buffer object is as follows:

StringBuffer sb = new StringBuffer();

Here, we have created an empty StringBuffer object with a default initial capacity of 16 characters and not passing any string to it.

To store a string into it, we can use append() method like this.

sb.append("Hello");

Now suppose 16 characters are completed. Can we add 17th character in the existing StringBuffer object?

Yes, if the StringBuffer object is full, still we can add 17th character to it. Once the capacity of StringBuffer object is filled, a new StringBuffer object will be created with bigger capacity.

All the 16th characters will be copied plus 17th character will be added. The reference variable sb will point to the new object and the old object by default will be gone to the garbage collector. But these total things will happen internally.


Q. What is the new capacity of a new StringBuffer object?

Ans: The capacity of a new StringBuffer object can be calculated by using the formula below:

New capacity = ( Current capacity + 1 ) * 2
Thus, New capacity = (16 + 1) * 2 = 34

Once the 16th character is completed, the next capacity will be 34 if we add 17th character.


Let’s take an example program based on it. Look at the program code to understand better.

Program code:

package stringBufferPrograms; 
public class CapacityTest { 
public static void main(String[ ] args) 
{ 
// Create a StringBuffer object. 
  StringBuffer sb = new StringBuffer(); 
   int length = sb.length(); 
   int capacity = sb.capacity(); 

   System.out.println("Before adding any character:"); 
   System.out.println("Length = " +length); // length = 0 
   System.out.println("Default initial capacity =  " +capacity); // Capacity = 16 
 
// Adding 16 characters in the existing string buffer object. 
   sb.append("abcdefghijklmnop"); 

   System.out.println("After adding 16 characters:"); 
   System.out.println("Length =  " +sb.length()); // now length is 16. 
   System.out.println("Capacity =  " +sb.capacity()); // still capacity is 16.

// Now add the 17th character in the existing string buffer object. 
   sb.append("q"); 

   System.out.println("After adding 17th character:"); 
   System.out.println("Length =  " +sb.length()); // length is 17
   System.out.println("Capacity =  " +sb.capacity()); // capacity is 34 
 
// Add 17 characters to the existing object. 
   sb.append("abcdefghijklmnopq"); // 17 characters. So, total = 34 characters. 

// Adding 35th character. 
   sb.append("r");  

   System.out.println("After adding 35th character:"); 
   System.out.println("Length =  " +sb.length()); // length is 35 
   System.out.println("Capacity =  " +sb.capacity()); // Capacity is 70
 } 
}
Output: 
          Before adding any character: 
          Length = 0 
          Default initial capacity = 16 
          
          After adding 16 characters: 
          Length = 16 
          Capacity = 16 
          
          After adding 17th character: 
          Length = 17 
          Capacity = 34 

          After adding 35th character: 
          Length = 35 
          Capacity = 70

As you can observe, up to the 16th character, still capacity is 16 only. This is because a new StringBuffer object has been created with a new capacity when we added the 17th character.

When 34 characters are completed and added 35th character then a new string buffer object with a bigger size is again created.

New capacity = ( 34 + 1 ) * 2 = 70.

Thus, StringBuffer has a growable nature. If the StringBuffer object reaches its maximum capacity, a bigger StringBuffer object is created internally.


Second way:

We can create an object of StringBuffer class by using the new operator and pass the string to the object. The general syntax to create StringBuffer object with the specified string is given below:

StringBuffer sb = new StringBuffer(String s);

For example:
   StringBuffer sb=new StringBuffer("Tech");
   Capacity = sb.length() + 16 = 4 + 16 = 20

Here, we are passing string “Tech” in the StringBuffer object and “sb” is pointing to that object i.e. the address of the StringBuffer object is stored in reference variable sb.

Let’s take an example program based on it.

Program code: 

package stringBufferPrograms; 
public class CapacityTest2 { 
public static void main(String[ ] args) 
{ 
 StringBuffer sb = new StringBuffer("Tech"); 
  int length = sb.length(); 
  int capacity = sb.length() + 16; 
  
  System.out.println(length); // 4 
  System.out.println(capacity); // 20 
  } 
}
Output:
            4 20

Third way: 

We can also create an empty StringBuffer object by declaring a size as an argument for storing characters. The general syntax is as follows:

StringBuffer sb = new StringBuffer(int initialCapacity);

For example:
      StringBuffer sb = new StringBuffer(30);

Here, an empty StringBuffer object has been created with a capacity for storing 30 characters. But it is also possible to store more than 30 characters in this object because StringBuffer is mutable and can expand dynamically in the memory.

What is Mutable String in Java?


A string that can be modified or changed into the existing object is known as mutable string. StringBuffer and StringBuilder classes are used to create a mutable string.

Let’s understand the mutable concept with the help of a simple example program and memory diagram.

Program code: 

package stringBufferPrograms; 
public class MutableStringEx { 
public static void main(String[ ] args) 
{ 
 StringBuffer sb = new StringBuffer("Scientech"); 
  sb.append(" Easy"); 
  System.out.println(sb); 
 } 
}
Output: 
           Scientech Easy

Explanation: 

Let’s understand the memory concept of this program with the help of figure below:

Mutable in Java
As you can observe in the above figure, no new object is created to add “Easy”. It is appended in the existing string buffer object because we can perform any required changes in the object when we create a StringBuffer object.

This changeable behavior is nothing but mutability in Java. The old object by default will be removed by the garbage collector.


Q. Are there any other classes except String class whose objects are immutable?

Ans: Yes, the wrapper classes such as Character, Byte, Integer, Float, Double, Long are immutable in nature. Classes like Class, BigInteger, BigDecimal are also created as immutable.

Why is String Constant Pool applicable only for String?


String constant pool is applicable only for string but not for StringBuffer. This is because string is the most common object used in Java whereas StringBuffer is rarely used in the application.

Therefore, Java language provides special memory management for a string. Without string, we cannot develop any application.

Let’s understand it with the help of an example program. In this program, we will use equals() method and double equal operator in the case of StringBuffer.

Program code: 

package stringBufferPrograms; 
public class Test { 
public static void main(String[ ] args) 
{ 
   StringBuffer sb1 = new StringBuffer("Hello"); 
   StringBuffer sb2 = new StringBuffer("Hello");  
 
   System.out.println(sb1 == sb2); 
   System.out.println(sb1.equals(sb2)); 
  } 
}
Output: 
            false 
            false

Explanation:

Let’s understand the program and its output with the help of figure below:

Why is String constant pool applicable only for String

Whenever we create a string buffer object using new operator, compulsory a new object will be created in the heap area with content “Hello”.

Therefore, JVM will create two objects with content “Hello” and the reference variable sb1 and sb2 are pointing to both objects respectively.

1. (sb1 == sb2); will return false because both references are pointing to the different objects as shown in the above figure.

2. sb1.equals(sb2); will return false because in the case of StringBuffer, equals() method compare the content based on reference (i.e. address). Both references are pointing to different objects.


Key points:

1. In case of StringBuffer, equals() method does not override the equals() method of object class.

2. If we call it using a reference variable, object class equals() method will be called. Object class equals() method compares references, not content as in string.

Need/Use for StringBuffer if String is already available in Java


In this section, we will discuss the need for StringBuffer class in Java. There are some such cases where we can not recommend using a string concept. For example,

1. When content is fixed and it will not change frequently. In this case, String class should be used.

2. If the content is not fixed and frequently changing but thread safety is also required, in this case, we should use the StringBuffer class.

Let’s understand the use of StringBuffer with the help of a suitable example.

Suppose that we have a string “Hello” in string constant pool and it is fixed and not changing frequently, we will need string class. Till now there is no problem.

Now assume that we want to add content “Java” with string “Hello”. In this case, compulsory a new object will be created with this change because a string object is immutable. We are not allowed to change in the existing object.

Now suppose the content is changing 10 times internally. This means that 10 times new objects will be created if the string will be used. In this situation, performance will be gone to be down. Memory problems will also be created in such a situation.

To overcome this kind of requirement, we should need or use a StringBuffer. If we will use StringBuffer object and 10 times content is changing then still one object will be created.

All the required changes will be performed in the existing object only. But if it is string, for every small change, a new object will be created.

Due to which memory will waste and performance will be down. This is the biggest advantage of StringBuffer technique in Java programming.


Key points:

1. In the case of String, for every small change, a new object will be created.

2. If StringBuffer is used, for all required changes, will perform in the existing object only. No new object will be created in the memory by JVM.


Hope that this tutorial has covered almost all the important points related to StringBuffer class in java with example programs. I hope that you will have understood the basic concepts of StringBuffer and enjoyed this tutorial.
Thanks for reading!!!
Next ⇒ StringBuffer Methods in Java

⇐ Prev Next ⇒