Fill your College Details

Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

String Buffer In Java: A Complete Guide

12 Sep 2025
5 min read

One of the most significant classes among the several string manipulation tools that Java offers is the String Buffer. The String Buffer provides a changeable method of handling strings that permits dynamic updates without generating additional objects, in contrast to the immutable String class. This feature is important for applications requiring frequent string operations, as it optimizes performance and memory usage.

This detailed guide explores the string and string buffer in Java, features, constructors, methods, and use cases, highlighting its significance in Java programming.

What is String Buffer?

A StringBuffer in Java is a class used to create and manage mutable strings. Unlike string classes, whose objects cannot be replaced once created, a StringBuffer allows modifications such as appending, inserting, removing or reversing without generating a new object every time. It is thread-safe as its methods are synchronized, which makes it suitable for use in multi-threaded environment.

Key Features of String Buffer in Java

  • Mutability: One of the most important benefits of StringBuffer is its mutation. Unlike string, which creates a new object for each modification, the StringBuffer allows direct changes to the existing object.
  • Thread Safety: The methods in StringBuffer are synchronized, ensuring that it is thread-safe. This means that multiple threads can work with the same StringBuffer object without causing data corruption.
  • Dynamic Resizing: StringBuffer automatically manages its capacity. When the current buffer is insufficient to hold additional characters, it increases its capacity, stopping the need to allocate space manually.
  • Integration with StringBuilder: While both StringBuffer and StringBuilder provide similar functionalities, the primary difference lies in thread safety. StringBuilder is optimized for single-threaded scenarios, but StringBuffer is designed for concurrent use.
  • Backward Compatibility: It inherits some of the methods from the Object class which such as clone(), equals(), finalize(), getClass(), hashCode(), notifies(), notifyAll().

Java provides multiple tools for string manipulation, and the String Buffer in Java is one of the most important classes among them. StringBuffer offers a mutant method of handling strings that permits dynamic updates without generating a lot of instances, as contrasted to the irreversible string class. Because it maximises efficiency and memory utilisation, this functionality is crucial for applications that need to perform string operations often.

🎯 Calculate your GPA instantly — No formulas needed!!

String Buffer Program in Java

String Buffer in Java is not only efficient but also versatile, offering multiple methods to manipulate strings seamlessly. Here is a complete example of using String Buffer 

String Buffer Program in Java to Concatenate Strings in Java:

Algorithm

  1. Initialization: Create an instance of StringBuffer initialized with "Hello".
  2. Append Operation: Add " World" and "!" to the sequence.
  3. Insert Operation: Insert "Java " at the 6th index of the buffer.
  4. Delete Operation: Remove the substring from index 11 to 16.
  5. Replace Operation: Replace the text from index 6 to 10 with "Programmers".
  6. Conversion and Output: Convert the StringBuffer to a String and display the final result.
public class StringBufferExample {
    public static void main(String[] args) {
        // Create a StringBuffer instance
        StringBuffer sb = new StringBuffer("Hello");
        
        // Append strings to the StringBuffer
        sb.append(" World");
        sb.append("!");
        
        // Insert a string at a specific position
        sb.insert(6, "Java ");
        
        // Delete a substring
        sb.delete(11, 16);
        
        // Replace a substring
        sb.replace(6, 10, "Programmers");
        
        // Convert StringBuffer to String and print the result
        String result = sb.toString();
        System.out.println("Final String: " + result);
    }
}

Output

Final String: Hello Programmers!

Explanation of the Code

In the code, we use String Buffer in Java to perform efficient string manipulations. The append method adds new strings to the end of the existing sequence, while the insert method allows inserting text at a specified position (index 6, in this case). The delete method removes a substring between specified indices, and replace substitutes a part of the string with new content. Finally, we convert the StringBuffer object to a String using the toString() method and print the result.

Complexity of the Code

  • Time Complexity: Append, insert, delete, and replace operations in StringBuffer are O(n), where nnn is the length of the string being operated on or shifted. Converting StringBuffer to String is also O(n).
  • Space Complexity: The space complexity is O(n), where n is the length of the StringBuffer. Additional temporary space may be required for specific operations.

Constructors of String Buffer

The String Buffer in Java provides several constructors that allow developers to initialize objects with different configurations. Each constructor performs a unique purpose in various use cases based on the required capacity or initial content. Here are the available constructors, explained in detail:

custom img

1. Default Constructor

The default constructor creates a StringBuffer object with an initial capacity of 16 characters. If more characters are added beyond this capacity, the buffer automatically resizes. This constructor is suitable when no specific string or capacity is needed during initialization.

Syntax:

StringBuffer sb = new StringBuffer();

Example Use Case: Useful when starting with an empty buffer and appending content later.

2. Constructor with Initial Capacity

This constructor allows specifying an initial capacity for the buffer, which helps optimize performance by reducing the need for frequent resizing when the expected content size is known in advance.

Syntax:

StringBuffer sb = new StringBuffer(50);

Example Use Case: Ideal for scenarios where you anticipate appending a large number of characters, e.g., dynamically building long strings in loops.

3. Constructor with String

This constructor initializes the StringBuffer with a specified string. The initial capacity of the buffer is the length of the provided string plus 16. This ensures that additional characters can be appended without immediate resizing.

Syntax:

 StringBuffer sb = new StringBuffer("Hello");

Example Use Case: Useful when starting with a predefined string and adding more content to it.

4. Constructor with CharSequence

This constructor accepts a CharSequence (e.g., String, StringBuilder, StringBuffer, etc.) as an argument to initialize the buffer. This makes it flexible and compatible with other sequence types.

Syntax:

CharSequence cs = "Example";
StringBuffer sb = new StringBuffer(cs);

Example Use Case: Allows seamless integration with other character sequence implementations.

Common Methods and Their Usage in StringBuffer

The StringBuffer class in Java provides a robust set of methods for efficient, dynamic string manipulation. Below are the most frequently used methods—append(), insert(), replace(), delete(), reverse(), capacity(), and length()—along with their typical use cases and practical examples.

1. append()

Appends the specified string, character, or value (e.g., integer, boolean) to the buffer. The content is added to the end of the existing sequence.

Syntax:

sb.append(value);

Example:

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World!");
System.out.println(sb); // Output: Hello World!

Use Case: Ideal for concatenating multiple strings efficiently without creating new objects.

2. insert()

Inserts a string, character, or value at the specified index. Existing characters are shifted to accommodate the new content.

Syntax:

sb.insert(index, value);

Example:

sb.insert(5, " Java");
System.out.println(sb); // Output: Hello Java World!

Use Case: Useful for inserting text at specific positions within a string.

3. delete()

Removes a substring from the buffer, defined by the starting and ending indices (exclusive).

Syntax:

sb.delete(startIndex, endIndex);

Example:

sb.delete(5, 10);
System.out.println(sb); // Output: Hello World!

Use Case: Handy for removing unwanted portions of a string dynamically.

3A. deleteCharAt()

The deleteCharAt(int index) method in Java removes the character at the specified index from a StringBuilder or StringBuffer object.

Syntax:

stringBuilder.deleteCharAt(int index);

Example:

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        sb.deleteCharAt(1); // Removes character at index 1 ('e')
        System.out.println(sb); // Output: Hllo
    }
}

Output:

Hllo

4. reverse()

Reverses the sequence of characters in the buffer.

Syntax:

sb.reverse();

Example:

sb.reverse();
System.out.println(sb); // Output: !dlroW olleH

Use Case: Commonly used in tasks requiring reversed text, like creating palindromes or reversing user input.

5. capacity()

Returns the current capacity of the buffer, which reflects the total amount of storage available before resizing.

Syntax:

sb.capacity();

Example:

System.out.println(sb.capacity()); // Output: 16 (default) 

Use Case: Useful for monitoring and optimizing memory usage during string operations.

6. ensureCapacity()

Confirms the buffer can hold at least the specified number of characters. If the current capacity is less than the specified value, it increases the buffer's capacity.

Syntax:

sb.ensureCapacity(minCapacity);

Example:

sb.ensureCapacity(100);

Use Case: Prevents frequent resizing in scenarios requiring large-scale string modifications.

7. length()

Returns back how many characters at present reside in the buffer.

Syntax:

sb.length();

Example:

System.out.println(sb.length()); // Output: 12 (length of "Hello World!")

Use Case: Helps track the actual content size within the buffer.

8. charAt()

Fetches the character located at the specified index in the buffer.

Syntax:

sb.charAt(index);

Example:

System.out.println(sb.charAt(0)); // Output: H

Use Case: Useful for retrieving specific characters, such as when parsing strings.

9. substring()

It extracts part of the string from the buffer as the new chain object. The original buffer remains unchanged.

Syntax:

sb.substring(startIndex, endIndex);

Example:

System.out.println(sb.substring(0, 5)); // Output: Hello

Use Case: Ideal for isolating specific parts of a string for further processing.

Using these techniques, developers can carry out multiple string manipulations quickly, ensuring both excellent performance and the ability to manage ever-changing text with ease.

10. replace()

The replace() method in Java replaces characters or substrings in String, StringBuilder, or StringBuffer.

Syntax:

String newStr = str.replace(char oldChar, char newChar);
String newStr = str.replace(CharSequence target, CharSequence replacement);

Differences between String and String Buffer in Java

Since strings are immutable, any changes they make result in a new object, which might cause slower performance and more memory usage. In contrast, StringBuffer is mutable, allowing changes directly to the existing object. 

StringBuffer confirms thread safety through methods which makes it more suitable for multi-threaded environments and faster for frequent modifications. Here are the difference between string and string buffer in Java:

Feature String StringBuffer
Mutability Immutable. Each modification creates a new object, leading to higher memory usage. Mutable. Changes are made directly to the original object.
Thread Safety Not thread-safe. Concurrent modifications can lead to data inconsistencies. Thread-safe. All methods are synchronized, ensuring safe operations in multi-threaded environments.
Performance Slower for operations involving frequent modifications (e.g., concatenation). Faster for frequent string operations, as it avoids creating new objects for each modification.

Difference between String Buffer and String Builder

String Buffer in Java is perfect for numerous threads where data consistency is needed since its methods are synchronised, making it thread-safe. Nevertheless, the slower synchronisation direction is introduced by this thread safety. Here are the differences between string buffer and string builder:

Feature StringBuffer StringBuilder
Thread Safety Thread-safe. Methods are synchronized, making it suitable for concurrent usage Not thread-safe. No synchronization, which makes it unsafe in multi-threaded scenarios.
Performance Slower due to synchronization overhead. Faster in single-threaded environments as it avoids synchronization.

Practical Use Cases of StringBuffer

When string manipulation calls for both speed and memory efficiency, Java's StringBuffer class is a useful friend. Here are some real-world examples of how this class excels and produces noticeable gains in performance.

1. Building Dynamic Strings

StringBuffer is ideal for constructing dynamic strings, such as concatenating user inputs or creating complex text-based reports, thanks to its mutability and efficiency.

2. Multi-threaded String Manipulation

Due to its thread-safe architecture, it works well with string operations in multi-threaded settings, such as analytics, logging, and concurrent data processing systems.

Example Program for Multi-threaded String Manipulation using String Buffer in Java:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Welcome");

        // Append
        sb.append(" to Java");
        System.out.println(sb); // Output: Welcome to Java

        // Insert
        sb.insert(7, " StringBuffer");
        System.out.println(sb); // Output: Welcome StringBuffer to Java

        // Reverse
        sb.reverse();
        System.out.println(sb); // Output: avaJ ot reffuBgnirtS emocleW

        // Capacity
        System.out.println("Capacity: " + sb.capacity());
    }
}

Output of the Code:

Welcome to Java
Welcome StringBuffer to Java
!avaJ ot reffuBgnirtS emocleW
Capacity: 34

Explanation of the Code:

In this code, we create a StringBuffer object initialized with the string "Welcome". The append() method is then used to add " to Java" to the existing content, resulting in the string "Welcome to Java". After that, the insert() method inserts the string " StringBuffer" at index 7, modifying the string to "Welcome StringBuffer to Java". The reverse() method is then called to reverse the entire string, which transforms it into "!avaJ ot reffuBgnirtS emocleW".

The capacity() method, that returns the StringBuffer's current capacity, is used in the last step to show how to use it. Initially, the capacity is 23, but it increases to 34 after all the modifications. This demonstrates how the StringBuffer dynamically adjusts its capacity to accommodate the growing string.

Advantages and Disadvantages of Using StringBuffer in Java

Understanding the strengths and limitations of StringBuffer is essential for making informed decisions about string manipulation in Java applications. Below is a focused overview of the key advantages and disadvantages, based on how StringBuffer operates and its role in multithreaded environments.

Advantages of StringBuffer

  1. Mutability for Efficient String Manipulation
    StringBuffer objects are mutable, enabling direct modifications such as appending, inserting, deleting, or replacing characters without creating new objects. This is particularly beneficial for applications that require frequent or complex string operations, as it leads to better performance and memory utilization.
  2. Thread Safety Through Synchronization
    All methods in StringBuffer are synchronized, making it inherently thread-safe. This design ensures that multiple threads can modify the same StringBuffer instance without causing data corruption or race conditions. As a result, StringBuffer is a reliable choice for string manipulation in multithreaded environments.
  3. Dynamic Capacity Management
    StringBuffer automatically manages its internal capacity. When more space is needed, it resizes itself to accommodate additional characters, reducing the need for manual memory management and minimizing the risk of running out of buffer space during string operations.
  4. Backward Compatibility
    As one of the original mutable string classes in Java, StringBuffer provides backward compatibility for legacy codebases. It remains a dependable option for maintaining and updating older Java applications where thread safety is a concern.

Disadvantages of StringBuffer

  1. Performance Overhead Due to Synchronization
    The synchronization that ensures thread safety also introduces performance overhead. In single-threaded scenarios, this can make StringBuffer slower than alternatives like StringBuilder, which offers similar mutability without synchronization.
  2. Less Efficient Than StringBuilder in Single-Threaded Contexts
    For applications that do not require thread safety, using StringBuffer can be less efficient than using StringBuilder. The extra cost of synchronization is unnecessary when only one thread is accessing the object, leading to slower execution.
  3. Not as Convenient as the ‘+’ Operator for Simple Concatenation
    While StringBuffer excels in complex or repetitive string operations, for simple or occasional concatenation, the ‘+’ operator or StringBuilder may offer more concise syntax and better performance.

When to Use StringBuffer

  • Choose StringBuffer when your application involves frequent string modifications in a multithreaded environment and thread safety is a priority.
  • For single-threaded scenarios or when thread safety is not required, prefer StringBuilder for better performance.

Conclusion

In summary, String Buffer in Java is a clever choice for dynamic string manipulation. It lets you edit text in place, unlike the immutable String type, so less copying happens, less memory is wasted, and programs run a bit faster. 

Its thread-safe nature makes it suitable for multi-threaded applications, while its methods, such as append(), insert (), and reverse(), provide flexibility in string operations. However, due to synchronization, a slightly slow StringBuffer excels in scenarios that require frequent and concurrent string modifications.

Frequently Asked Questions

1. What is a String Buffer in Java?

The java.lang package contains the mutable character sequence known as StringBuffer. It allows for efficient manipulation of strings by modifying the existing object, unlike String, which creates a new object on each modification.

2. What is the difference between StringBuffer and StringBuilder in Java?

The main distinction is that StringBuffer is synchronised and thread-safe, which makes it appropriate for multi-threaded contexts, whereas StringBuilder is not, which makes it faster in situations involving only one thread.

3. What is buffer in Java?

In Java, a buffer serves as a temporary holding cell for data, commonly popping up during input and output scenarios to better the overall speed of the process. When you’re pulling information from a file or sending data to a network socket, the journey is quicker if it first pauses in a buffer rather than going straight to its final destination.

4. What are the constructors available for StringBuffer?

The StringBuffer class offers a handful of constructors: one that accepts an initial capacity, a second that lets you specify how many characters it can initially hold, another that initializes the buffer with the contents of a string, and a final option that accepts any object that matches the CharSequence interface.

5. How does StringBuffer improve performance over String?

Because StringBuffer keeps its memory space and simply modifies the contents, it dodges the cost of making a whole new object with every small change to a string. By reusing the same space, it performs better under the sort of chores—concatenation, insertion, or deletion, where you would otherwise risk a lot of mini object-creating operations, each of which slows things down if the job gets busy.

6. Is StringBuffer thread-safe?

Because its operations are synchronised, StringBuffer is indeed thread-safe, meaning that several threads can safely alter the buffer at the same time without corrupting data.

7. Can StringBuffer be used for concatenating strings in Java?

Yes, StringBuffer is commonly used for concatenating strings as it provides the append() method, which allows efficient string concatenation without creating multiple intermediate objects.

8. What is the difference between String and String Buffer in Java?

A String in Java is immutable, which means that once it is formed, its value cannot be altered. A StringBuffer, on the other hand, can be changed by appending, inserting, or deleting data without generating a new object. Although both String and StringBuffer in Java are used to handle text, String is preferred for fixed values, and StringBuffer is better when frequent updates to the text are required.

Read More Articles

Chat with us
Chat with us
Talk to career expert