StringBuffer class

The StringBuffer class is part of the java.lang package and is used to create and manipulate mutable (modifiable) strings in Java. Unlike the String class, which is immutable, the StringBuffer class allows you to modify the contents of a string without creating new objects each time, which improves performance when performing repeated string concatenation or modifications.

Key Features of StringBuffer:

  1. Mutability:

    • StringBuffer objects are mutable, meaning their contents can be modified without creating new objects. This is in contrast to String, which is immutable.

  2. Thread Safety:

    • StringBuffer is synchronized, meaning it is thread-safe. Multiple threads can safely access and modify a StringBuffer instance without causing data inconsistency or corruption. However, this synchronization comes with some performance overhead.

  3. Performance:

    • StringBuffer is generally faster than using String concatenation (with the + operator) in loops or repeated modifications because it doesn’t create intermediate objects like String does.

  4. Capacity Management:

    • StringBuffer has a capacity that is automatically adjusted as the string grows. If the length exceeds the current capacity, the buffer is resized automatically to accommodate the new string.

StringBuffer Constructors:

Default constructor: Creates an empty StringBuffer with a default capacity (16 characters).

StringBuffer sb = new StringBuffer();Code language: JavaScript (javascript)

Constructor with an initial capacity: Creates a StringBuffer with a specific initial capacity.

StringBuffer sb = new StringBuffer(50); // Initial capacity of 50Code language: JavaScript (javascript)

Constructor with a string argument: Initializes a StringBuffer with the specified string.

StringBuffer sb = new StringBuffer("Hello");Code language: JavaScript (javascript)

StringBuffer Methods with Complete Syntax and Description

Method Syntax Description
append(String str) StringBuffer append(String str) Appends the specified string to the end of the current StringBuffer.
append(int i) StringBuffer append(int i) Appends the string representation of the specified integer to the end of the StringBuffer.
append(char c) StringBuffer append(char c) Appends the string representation of the specified character to the end of the StringBuffer.
insert(int offset, String str) StringBuffer insert(int offset, String str) Inserts the specified string at the given position (offset) in the StringBuffer.
insert(int offset, int i) StringBuffer insert(int offset, int i) Inserts the string representation of the specified integer at the given offset position.
insert(int offset, char c) StringBuffer insert(int offset, char c) Inserts the specified character at the given offset position.
delete(int start, int end) StringBuffer delete(int start, int end) Removes characters from the specified start index to end index.
deleteCharAt(int index) StringBuffer deleteCharAt(int index) Deletes the character at the specified index.
reverse() StringBuffer reverse() Reverses the entire content of the StringBuffer.
replace(int start, int end, String str) StringBuffer replace(int start, int end, String str) Replaces the characters in the specified range with the specified string.
setCharAt(int index, char ch) void setCharAt(int index, char ch) Sets the character at the specified index to the specified character.
substring(int start) String substring(int start) Returns a new String that contains the substring starting from the specified index.
substring(int start, int end) String substring(int start, int end) Returns a new String that contains the substring from start to end index.
length() int length() Returns the length of the StringBuffer.
capacity() int capacity() Returns the current capacity of the StringBuffer.
ensureCapacity(int minimumCapacity) void ensureCapacity(int minimumCapacity) Ensures that the StringBuffer has at least the specified minimum capacity.
setLength(int newLength) void setLength(int newLength) Sets the length of the StringBuffer. If the new length is less than the current length, the buffer is truncated.
charAt(int index) char charAt(int index) Returns the character at the specified index.
indexOf(String str) int indexOf(String str) Returns the index of the first occurrence of the specified string in the StringBuffer.
indexOf(String str, int fromIndex) int indexOf(String str, int fromIndex) Returns the index of the first occurrence of the specified string, starting the search at the specified index.
lastIndexOf(String str) int lastIndexOf(String str) Returns the index of the last occurrence of the specified string in the StringBuffer.
lastIndexOf(String str, int fromIndex) int lastIndexOf(String str, int fromIndex) Returns the index of the last occurrence of the specified string, starting the search backward from the specified index.
toString() String toString() Converts the contents of the StringBuffer to a String.

Program

public class StringBufferExample {

    public static void main(String[] args) {
        // Create a new StringBuffer with LotusJavaPrince's name
        StringBuffer sb = new StringBuffer("LotusJavaPrince");
        System.out.println("Initial String: " + sb);

        // Append Mahesh to the string
        sb.append(" and Mahesh");
        System.out.println("After Append: " + sb);

        // Insert a designation at a specific position
        sb.insert(14, " (Developer)");
        System.out.println("After Insertion: " + sb);

        // Replace "Developer" with "Lead Developer"
        int startIndex = sb.indexOf("Developer");
        int endIndex = startIndex + "Developer".length();
        sb.replace(startIndex, endIndex, "Lead Developer");
        System.out.println("After Replacement: " + sb);

        // Delete the space between "Lead" and "Developer"
        sb.deleteCharAt(sb.indexOf(" "));
        System.out.println("After Deletion: " + sb);

        // Reverse the entire string
        sb.reverse();
        System.out.println("After Reversing: " + sb);
    }
}
/*
Initial String: LotusJavaPrince  
After Append: LotusJavaPrince and Mahesh  
After Insertion: LotusJavaPrince (Developer) and Mahesh  
After Replacement: LotusJavaPrince (LeadDeveloper) and Mahesh  
After Deletion: LotusJavaPrince (LeadDeveloper)and Mahesh  
After Reversing: hsehaM dna)repoleveDdaeL( ecnevirPavaJsutoL  
*/

The StringBuffer class in Java provides a mutable sequence of characters, making it ideal for scenarios involving frequent modifications to strings without creating multiple objects. It offers various methods like append(), insert(), replace(), delete(), and reverse() to efficiently perform operations on strings. Unlike String, which is immutable, StringBuffer ensures that changes are reflected in the same object, leading to better memory management. Additionally, it is thread-safe due to its synchronized methods, making it suitable for multi-threaded applications. However, for single-threaded contexts, StringBuilder is preferred for better performance.

Leave a Comment

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

Scroll to Top