StringBuffer is a predefined class in the Java programming language. This class stores a mutable sequence of different types, which means we can update the sequence according to our needs. StringBuffer is a superclass of String in Java. This class provides various methods for deleting and updating the sequence of elements.
What is a StringBuffer in Java?
StringBuffer is a Java class that represents a mutable sequence of characters. It is very similar to the String class in Java. However, it provides some methods for modifying the string without creating an instance of the same string object. This class allows developers to append, insert, and delete characters within the string. Let’s dive deep into the StringBuffer class.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Syntax of StringBuffer class
In Java, the StringBuffer class extends two interfaces, CharSequence and Serializable.
Syntax
public final class StringBuffer
extends Object
implements Serializable, CharSequence
Creating a StringBuffer Object
To start using the ‘StringBuffer” class. You need to create a StringBuffer Object. We can create a StringBuffer class object by using the default constructor or by passing the initial string to the constructor.
Program
import java.io.* ;
class StringBufferExample{
public static void main(String args[]){
StringBuffer stringBuffer1 = new StringBuffer();
StringBuffer stringBuffer2 = new StringBuffer("Hello");
System.out.println(stringBuffer2) ;
}
}
Output
Hello
Class Declaration
We can create a StringBuffer Object class using the new keyword as we would a normal class object. However, the StringBuffer class is not a primitive class, which means we cannot assign a direct value to it. The following program shows “how we can use the StringBuffer class.”
Program
public class StringBufferExample {
public static void main(String[] args) {
// Create a new StringBuffer object
StringBuffer stringBuffer = new StringBuffer();
// Append some strings
stringBuffer.append("Hello");
stringBuffer.append(" ");
stringBuffer.append("World");
System.out.println(stringBuffer);
}
}
Output
Hello World
Importance of Constructors of StringBuffer class in Java
There are many constructors in the StringBuffer class. Constructor is a special method in Java programming language that is used to initialize objects. Constructors are called when we create the class object. It can also pass arguments to the Constructors. Let’s discuss different Constructors in the Java Programming language.
StringBuffer(): This constructor is used for creating a StringBuffer class with no characters. This constructor’s initial capacity is 16 bytes. This constructor does not require any parameters.
Syntax: StringBuffer ob = new StringBuffer();
StringBuffer(int capacity): This constructor initializes the string StringBuffer’s initial size. It takes only one parameter, capacity, which is an integer type.
Syntax:StringBuffer ob = new StringBuffer(15);
StringBuffer(string): This constructor takes only one parameter, which is the string type. This string converts into the StringBuffer object using the StringBuffer class. The default capacity of the StringBuffer is 16 bytes.
Syntax:StringBuffer ob = new StringBuffer(String);
StringBuffer(char sequence): This constructor is used for creating a StringBuilder of character sequence. This constructor takes only one parameter, which is the charsequence.
StringBuffer ob = new StringBuffer(CharSequence);
Methods of StringBuffer
StringBuffer class provides different methods inbuilt methods in Java programming language. Let’s discuss each method one by one with examples.
append() method: This inbuilt method is used for appending the new string with the existing string of the StringBuffer class in Java.
Syntax of append() method
public StringBuffer append(datatype)
Program
import java.io.*;
class AppendMethodExammple {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
Output
Hello Java
insert() Method: This method inserts the string at the given string at the given position.
Program
import java.io.*;
class InsertMethodExample {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now the original string is changed
System.out.println(sb);
}
}
Output
HJavaello
replace() method: The replace() method replaces the given string from the specified beginIndex and endIndex 1 of the string.
Program
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(1, 8, "Java");
System.out.println(sb);
}
}
Output
HJavarld
delete() method: This delete() method of the StringBuffer class deletes the string by passing the specified beginIndex to endIndex-1.
Program
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("WorldComputer");
sb.delete(1, 3);
System.out.println(sb);
}
}
Output
WldComputer
reverse() method: The reverse() method is also an inbuilt method in the Java StringBuffer class. It reverses the current string.
Program
import java.io.* ;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Neeraj Kumar");
sb.reverse();
System.out.println(sb);
}
}
Output
ramuK jareeN
capacity() method: The capacity() method of the StringBuffer class returns the capacity of the buffer. The default capacity of the StringBuffer is 16. If the number of characters is increased, its capacity also increases by (oldcapacity 2) +2. For example, If your current capacity is 16. It will be (16*2) = 32
Program
import java.io.*;
class CapacityExample {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
sb.append("Hello, I am Ninja");
System.out.println(sb.capacity());
sb.append("Hello, Computer language");
System.out.println(sb.capacity());
}
}
Output
16
34
70
StringBuffer.length(): The method returns the length of the current buffer string object sequence. The length of the StringBuffer is always smaller and equal to the capacity of the StringBuffer method capacity.
Program
import java.lang.*;
public class Demo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Neeraj Kumar ");
System.out.println("The given string is: " + sb);
int length = sb.length();
System.out.println("The length of the '" + sb + "' is: " + length);
}
}
Output
The given string is: Neeraj Kumar
The length of the 'Neeraj Kumar ' is: 13
Inherited Methods of StringBuffer in Java
In this section, we will discuss the Inherited Methods of StringBuffer in Java. The StringBuffer class inherited the ObjectClass, which is the parent of all Java classes in the Java programming language.
hashCode() method: This method generates the hash value of the particular StringBuffer class. This hash value is used for comparison to two StringBuffer class objects.
Program
import java.io.*;
class CapacityExample {
public static void main(String args[])
{
//Creating the instance of StringBuffer class
StringBuffer m=new StringBuffer();
//Printing the hashCode of StringBuffer object
System.out.println(m.hashCode());
}
}
Output
212628335
equals() method: This method is used to compare two objects of the StringBuffer class in Java. Internally, Java uses the hasCode() method for the comparison of two objects.
If the hash code of two objects is equal, then this method returns true; otherwise, it returns false.
Note: This method returns false because both strings are references, So the hash value is not the same.
Program
import java.lang.*;
public class Demo {
public static void main(String[] args) {
StringBuffer firstString =new StringBuffer("Neeraj");
StringBuffer secondString=new StringBuffer("Neeraj");
System.out.println(firstString.equals(secondString));
}
}
Output
False
getClass() method: This method is used for getting the expat path of the class where it is present in the JDK(Java Development Kit). This method returns the
Path of the class in the String format.
Program
import java.lang.*;
public class GetClassExample {
public static void main(String[] args) {
StringBuffer m = new StringBuffer();
//Returning the classpath of StringBuffer
System.out.println(m.getClass());
}
}
Output
class java.lang.StringBuffer
toString(): This method converts the StringBuffer object into the String. This method does not have any parameters. This method returns the string.
Program
import java.lang.*;
public class GetClassExample {
public static void main(String[] args) {
StringBuffer ob = new StringBuffer();
ob.append("Neeraj Kumar");
System.out.println(ob.toString());
}
}
Output
Neeraj Kumar
Advantages of StringBuffer
The StringBuffer class in Java provides several advantages over the normal ‘string’ class. Here are some common advantages of the StringBuffer class:
StringBuffer is Mutable: Strings objects are immutable, which means we cannot change the content after it has been created. However, StringBuffer is mutable, which means we can update the string object after it has been created.
Efficient Concatenation: StringBuffer is mutable so we can update and delete the character from the StringBuffer easily, which makes StringBuffer efficient as compared to StringBuffer.
Versatile API: StringBuffer provides various methods for string manipulations, including append, insert, delete, replace, and reverse methods. These methods provide flexibility for manipulating the string operations.
Thread Safe: StringBuffer objects are thread-safe, and multiple threads can access the StringBuffer class. It can be modified easily by StringBuffer. In contrast, Strings objects are not thread-safe, which means you need synchronization. If you want to access a string of objects from multiple threads.
Disadvantages of StringBuffer
StringBuffer also has some limitations. Here are some disadvantages of the StringBuffer class:
Performance Overhead: StringBuffer provides efficient string manipulations. It is the thread-safe class that introduces performance overhead, especially in single-threaded applications. Sometimes, thread safety does not require it, which is why Java introduced the StringBuilder class.
Mutable State: The StringBuffer object is mutable. This means we can change its contents. However, this mutable state can sometimes introduce complexity and potential bugs, especially in large or complex databases where tracking the state changes of “StringBuffer” becomes challenging for developers.
Memory Overhead: StringBuffer maintains the internal character array buffer to store the string content, which consumes additional memory compared to immutable strings. In scenarios where the developers create a large number of StringBuffer objects or the string content is very small, this memory overhead significantly impacts the overall memory usage of computer applications.
Conclusion
StringBuffer in Java provides a powerful and flexible mechanism for dynamic string manipulation. It offers different methods for appending, inserting, deleting, replacing, and manipulating strings. StringBuffer is mutable, allowing developers to modify it, reducing memory overhead and improving performance. By Understanding StringBuffer methods and utilizing them effectively, developers can leverage the power of “StringBuffer” to enhance the functionality and performance of their Java applications.
FAQs
What is a StringBuffer class in Java?
StringBuffer is an inbuilt class in Java that represents a mutable sequence of characters. It allows for the modification of the string without creating a new object each time. Strings are not mutable in Java.
What are the advantages of using ‘StringBuffer’?
StringBuffer class provides various advantages like mutability, efficient string manipulation, thread safety, flexible capacity management, and a versatile set of methods in StringBuffer.
How do I convert a “StringBuffer" to a String?
We can convert the StringBuffer object to a String using the ‘toString()’ method. For example: “String str = stringBuffer.toString();’
Is the ‘StringBuffer’ thread-safe?
Yes, StringBuffer is thread-safe, meaning its methods are synchronized to ensure safe access by multiple threads simultaneously.
How do I reverse a string using “StringBuffer”?
We can reverse a string using the ‘reverse()’ method of ‘StringBuffer. For example ‘stringBuffer.reverse()’ method.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.