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. How to take string input and how to manipulate strings are essential. However, the 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
A 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 a Java mutable string?
Before starting the discussion about StringBuffer methods and constructors, we must know what exactly a mutable string is. Thus, A string that facilitates modification is known as a mutable string. However, 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 a String as a 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 its length. |
Let us discuss some of the important methods present in the Java StringBuffer class
1. Java append()
This method is used to concatenate two strings. Therefore, using the append() method in Java enables adding a string to the end of another string.
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:
2. Java insert()
The insert method inserts the given string into the StringBuffer object at the given position. However, the insert() method needs two parameters to be passed, which are:
- The first parameter is an integer value given at the position where the string will be added.
- The second parameter is a string itself that is to be added.
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:
3. Java replace()
The Java replace() method replaces the StringBuffer object with the specified string at the specified position.
However, It consists of the three parameters starting index and the ending index at which the string will be replaced and the third parameter is the new string that will replace the characters.
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:
4. Java delete()
Java delete() 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:
5. Java reverse()The
Java reverse() 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:
6. Java capacity()
The capacity() method returns the current capacity of the StringBuffer object. However, 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
57
7. Java ensureCapacity()
The ensureCapacity() method ensures that the given capacity is the minimum limit to the current capacity. Although 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
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:
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 the Java StringBuffer Class:
| SL. No. | Method Name and Return Type | Description |
| 1 | char charAt(int index) | Using this method, we can return the character present at the specified index. |
| 2 | int codePointAt(int index) | However, this method returns the Unicode code point of the character at the specified index. |
| 3 | int codePointBefore(int index) | Using this method, we can return the Unicode code point of the character before the specified index |
| 4 | int 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. |
| 5 | void ensureCapacity(int minimumCapacity) | This method ensures that the capacity of the StringBuffer object is at least equal to the given minimum capacity. |
| 6 | void 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. |
| 7 | int indexOf(String str, int fromIndex) | Using this method, we can return the first occurrence of the given substring from the given index. |
| 8 | StringBuffer insert(int offset, String str) | Using this method, we can insert the string into the specified string at the specified offset. |
| 9 | int lastIndexOf(String str) | Using this method, we can return the last occurrence of the given substring from the given index. |
| 10 | void setCharAt(int index, char ch) | Using this method, we can set a character at the specified index of the string. |
| 11 | void setLength(int newLength) | This method is used to change the length of a string and set the specified length. |
| 12 | String substring(int start, int end) | This method returns the portion of the string between the given range. |
| 13 | String toString() | This method converts a given data into a string and returns it. |
| 14 | void trimToSize() | This method is used to trim the size of the string. |
| 15 | CharSequence 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, and CharSequence.
- However, we can use multithreading in the StringBuffer class, if and only if all the methods are declared synchronized to work in a multithreaded environment.
- Although if an operation occurs involving a source sequence, the class synchronizes only on the StringBuffer operating, 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.
When it comes to string manipulation in a multithreaded environment, safety is paramount. Unlike its counterpart, StringBuilder, StringBuffer boasts thread safety. Thus, this means multiple threads can access and modify the same StringBuffer object concurrently without the risk of data corruption.
The magic behind this lies in StringBuffer is synchronized methods of StringBuffer. However, Synchronization acts as a gatekeeper, ensuring only one thread can modify the object at a time. Therefore, this controlled access makes StringBuffer the ideal choice for applications where multiple threads need to collaborate on building or modifying the same string data.
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.
Your opinion matters
Please write your valuable feedback about DataFlair on Google

