StringBuffer in Java – Explore its Constructors & Methods with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

We know that the human brain is capable of understanding words better than numbers. So, the only way to represent words in a program is through strings. Knowing how to take string input and how to manipulate strings is very essential. StringBuffer class enables programmers to take mutable string input and manipulate them at an ease. In this article, we will take a look at some of the most important StringBuffer methods in Java.

StringBuffer Class in Java:

String in general is a sequence of characters that is immutable in nature. But java provides a class called StringBuffer that facilitates the programmer to create a string that is mutable in nature.

Every class in java has two main attributes:
1. Constructors
2. Methods

Let us discuss the different constructors and methods that are part of the StringBuffer class.

What is Java mutable string?

Before starting the discussion about StringBuffer methods and constructors, we must know what exactly is a mutable string. A string that facilitates modification or change is known as a mutable string. The StringBuffer and StringBuilder classes allow us to create mutable strings.

StringBuffer Constructors in Java:

Constructor(Syntax)Description
StringBuffer()It is the default constructor of the StringBuffer class. This constructor creates an empty StringBuffer with an initial capacity of 16.
StringBuffer(String str)It is a parameterized constructor with String as Parameter. This constructor creates a StringBuffer with the specified string.
StringBuffer(int capacity)It is a parameterized constructor with an integer as a parameter. This constructor creates an empty StringBuffer with the specified capacity as length.

Let us discuss some of the important methods present in Java StringBuffer class:

1. Java append():

This method is used to concatenate two strings.

Code to understand Java append() method:

package com.DataFlair.Stringbuffer;
public class Append
{
    public static void main(String args[])
    {  
        StringBuffer str=new StringBuffer("Data");  
        str.append("Flair");  
        System.out.println(str);
    }  
}  

The output of the above code:

DataFlair

2. Java insert():

The insert method inserts the given string into the StringBuffer object at the given position.

Code to understand Java insert() method:

package com.DataFlair.Stringbuffer;
public class Insert
{
    public static void main(String args[])
    {  
        StringBuffer str=new StringBuffer("Data");  
        str.insert(4,"Flair"); 
        System.out.println(str);
    }  
} 

The output of the above code:

DataFlair

3. Java replace():

This method replaces the StringBuffer object with the specified string at the specified position.

Code to understand Java replace() method:

package com.DataFlair.Stringbuffer;
public class Replace
{
    public static void main(String args[])
    {  
        StringBuffer sb=new StringBuffer("Data");  
        sb.replace(2,3,"Flair");  
        System.out.println(sb); 
    }  
} 

The output of the above code:

DaFlaira

4. Java delete():

This method deletes the StringBuffer object from the specified position.

Code to understand Java delete() method:

package com.DataFlair.Stringbuffer;
public class Delete
{
    public static void main(String args[])
    {  
        StringBuffer sb=new StringBuffer("DataFlair");  
        sb.delete(4,9);  
        System.out.println(sb);
    } 
}

The output of the above code:

Data

5. Java reverse():

This method is used to reverse the String present in the StringBuffer object.

Code to understand Java reverse() method:

package com.DataFlair.Stringbuffer;
public class Reverse
{
    public static void main(String args[])
    {  
        StringBuffer str=new StringBuffer("DataFlair");  
        str.reverse();  
        System.out.println(str);
    }  
}  

The output of the above code:

rialFataD

6. Java capacity():

The capacity() method returns the current capacity of the StringBuffer object. The default capacity of the StringBuffer object is 16. If the number of characters increases from its current capacity, it increases the capacity by:(old capacity*2)+2. For example, if your current capacity is 16, then the capacity will be calculated as: (16*2)+2= 34.

Code to understand Java capacity() method:

package com.DataFlair.Stringbuffer;
public class Capacity
{
    public static void main(String args[])
    {  
        StringBuffer sb=new StringBuffer();  
        System.out.println(sb.capacity()); 
        sb.append("DataFlair");  
        System.out.println(sb.capacity()); 
        sb.append("DataFlair is company that teaches programming!!!");  
        System.out.println(sb.capacity());
    } 
}

The output of the above code:

16
16
57

7. Java ensureCapacity():

The ensureCapacity() method ensures that the given capacity is the minimum limit to the current capacity. If the capacity is greater than the current capacity, the method increases the capacity by (old capacity*2)+2. For example, if your current capacity is 32, it will be (32*2)+2=66.

Code to understand Java ensureCapacity() method:

package com.DataFlair.Stringbuffer;
public class EnsureCapacity
{
    public static void main(String args[])
    {
        StringBuffer sb=new StringBuffer();  
        System.out.println(sb.capacity());  
        sb.append("DataFlair");  
        System.out.println(sb.capacity());
        sb.append("DataFlair is company that teaches programming!!!");  
        System.out.println(sb.capacity()); 
        sb.ensureCapacity(10);
        System.out.println(sb.capacity());  
        sb.ensureCapacity(50);
        System.out.println(sb.capacity()); 
    }  
}  

The output of the above code:

16
16
57
57
57

8. Java deleteCharAt():

This method deletes the character at the specified index.

Code to understand Java deleteCharAt():

package com.DataFlair.Stringbuffer;
public class DeleteCharAt
{
    public static void main(String[] args) {
    StringBuffer str = new StringBuffer("DataFlair");
    System.out.println("Original String is: " + str);
    str.deleteCharAt(1);
    System.out.println("The String after deleting a character at 1st index: " + str);
    str.deleteCharAt(5);
    System.out.println("The String after deleting a character at 5th index: " + str);
  }
}

The output of the above code:

Original String is: DataFlair
The String after deleting a character at 1st index: DtaFlair
The String after deleting a character at 5th index: DtaFlir

List of some of the other methods of Java StringBuffer Class:

SL. No.Method Name and Return TypeDescription
1char charAt(int index)Using this method we can return the character present at the specified index.
2int codePointAt(int index)This method returns the Unicode code point of the character at the specified index.
3int codePointBefore(int index)Using this method we can return the Unicode code point of the character before the specified index
4int codePointCount(int beginIndex, int endIndex)Using this method we can return the number of Unicode code points in the String between the two endpoints specified.
5void ensureCapacity(int minimumCapacity)This method ensures that the capacity of the StringBuffer object is at least equal to the given minimum capacity.
6void getChars(int sourceBegin, int sourceEnd, char[] destination, int destBegin)Using this method we can copy the specified characters in a specific range to a specific destination character array.
7int indexOf(String str, int fromIndex)Using this method we can return the first occurrence of the given substring from the given index.
8StringBuffer insert(int offset, String str)Using this method we can insert the string into the specified string at the specified offset.
9int lastIndexOf(String str)Using this method we can return the last occurrence of the given substring from the given index.
10void setCharAt(int index, char ch)Using this method we can set a character at the specified index of the string.
11void setLength(int newLength)This method is used to change the length of a string and set the specified length.
12String substring(int start, int end)This method returns the portion of the string between the given range.
13String toString()This method converts a given data into a string and returns it.
14void trimToSize()This method is used to trim the size of the string.
15CharSequence subSequence(int start, int end)Using this method we can return a new character sequence from the specified range of indexes.

Points to Remember:

  • java.lang.StringBuffer class extends the Object class.
  • The StringBuffer class is implemented by the interfaces: Serializable, Appendable, CharSequence.
  • We can use multithread in the StringBuffer class, if and only if all the methods are declared synchronized to work in a multithread environment.
  • If an operation occurs involving a source sequence the class synchronizes only on the StringBuffer performing the operation, not on the source.
  • The StringBuffer class inherits some of the methods from the Object class which are: clone, equals, finalize, getClass, hashCode, notify, notifyAll.

Conclusion:

So, we can see that StringBuffer helps ease the process of string manipulation, by mutating the string. That is why it is important to know the working of StringBuffer, as String Handling is a key aspect of programming. In this article, we saw how to implement different methods of the StringBuffer class into our program.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

Leave a Reply

Your email address will not be published. Required fields are marked *