Java StringBuffer Class Explained for Beginners

0

1. StringBuffer Class in Java

The StringBuffer class is used to create mutable strings in Java.

Unlike the String class, StringBuffer objects can be modified without creating new objects repeatedly.

StringBuffer is similar to StringBuilder, but it is thread-safe.


2. Why StringBuffer is Used

StringBuffer is used when string modifications happen frequently and thread safety is required.

  • a. Reduces object creation
  • b. Improves memory efficiency
  • c. Supports mutable text operations
  • d. Provides thread safety
  • e. Useful in multi-threaded applications

3. Where StringBuffer is Used

StringBuffer is commonly used in systems where multiple threads work on shared text data.

  • a. Multi-threaded applications
  • b. Server-side applications
  • c. Logging systems
  • d. Dynamic report generation
  • e. Enterprise applications
  • f. Shared text processing systems

4. Creating StringBuffer Objects

A StringBuffer object can be created using different constructors.


4.1 Empty StringBuffer

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        System.out.println(buffer);
    }
}

This creates an empty StringBuffer object.


4.2 StringBuffer with Initial Text

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        System.out.println(buffer);
    }
}

The object is initialized with the text Java.


4.3 StringBuffer with Capacity

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer(50);

        System.out.println(buffer.capacity());
    }
}

The output shows the initial storage capacity.


The default capacity of StringBuffer is 16 characters.


5. append() Method

The append() method adds data at the end of the existing text.


5.1 Example of append()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.append(" Programming");

        System.out.println(buffer);
    }
}

The text Programming is added at the end.


5.2 Appending Different Data Types

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        buffer.append("Age: ");
        buffer.append(25);

        System.out.println(buffer);
    }
}

append() supports multiple data types such as integers, booleans, and characters.


6. insert() Method

The insert() method inserts text at a specific position.


6.1 Example of insert()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.insert(4, " Language");

        System.out.println(buffer);
    }
}

The text Language is inserted starting from index 4.


Providing an invalid index in insert() causes StringIndexOutOfBoundsException.


7. delete() Method

The delete() method removes characters from a specific range.


7.1 Example of delete()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java Programming");

        buffer.delete(4, 16);

        System.out.println(buffer);
    }
}

Characters between index 4 and 15 are removed from the text.


8. reverse() Method

The reverse() method reverses the character sequence.


8.1 Example of reverse()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.reverse();

        System.out.println(buffer);
    }
}

The output becomes avaJ.


9. replace() Method

The replace() method replaces characters between specified indexes.


9.1 Example of replace()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java Language");

        buffer.replace(5, 13, "Programming");

        System.out.println(buffer);
    }
}

The word Language is replaced with Programming.


The ending index is excluded during replacement.


10. deleteCharAt() Method

The deleteCharAt() method removes a single character from a specific position.


10.1 Example of deleteCharAt()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.deleteCharAt(1);

        System.out.println(buffer);
    }
}

The character at index 1 is removed from the text.


11. setCharAt() Method

The setCharAt() method changes a character at a specific index.


11.1 Example of setCharAt()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.setCharAt(0, 'K');

        System.out.println(buffer);
    }
}

The character J is replaced with K.


12. length() Method

The length() method returns the number of characters currently stored.


12.1 Example of length()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Programming");

        System.out.println(buffer.length());
    }
}

The output displays the total number of characters.


13. capacity() Method

The capacity() method returns the available storage capacity.


13.1 Default Capacity

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        System.out.println(buffer.capacity());
    }
}

The default capacity is 16.


13.2 Capacity Expansion

If storage becomes full, Java automatically increases the capacity.


public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        buffer.append("abcdefghijklmnopqrstuvwxyz");

        System.out.println(buffer.capacity());
    }
}

The capacity increases automatically when additional space is required.


Automatic resizing may allocate additional memory internally.


14. toString() Method

The toString() method converts a StringBuffer object into a String object.


14.1 Example of toString()

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        String result = buffer.toString();

        System.out.println(result);
    }
}

The mutable StringBuffer data is converted into an immutable String object.


15. Internal Working of StringBuffer

Internally, StringBuffer uses a resizable character array.


15.1 Mutable Internal Storage

Instead of creating new objects repeatedly, StringBuffer modifies the same internal character array.


StringBuffer buffer = new StringBuffer("Java");

buffer.append(" Programming");

The same object is modified internally.


15.2 Capacity Growth Formula

When storage becomes full, Java increases capacity using an internal formula.


newCapacity = (oldCapacity * 2) + 2

This strategy reduces frequent memory reallocation.


16. Synchronization in StringBuffer

StringBuffer methods are synchronized internally.

Synchronization allows multiple threads to safely access the same object.


16.1 Thread-Safe Operations

Only one thread can execute synchronized methods at a time.


StringBuffer buffer = new StringBuffer();

buffer.append("Java");

The append() method is internally synchronized for safe multi-threaded access.


Synchronization improves safety but slightly reduces performance.


17. Difference Between StringBuffer and StringBuilder

Both StringBuffer and StringBuilder are mutable classes used for modifying text data.

The major difference is thread safety.


Feature StringBuffer StringBuilder
Thread Safety Yes No
Synchronization Synchronized Not synchronized
Performance Slower Faster
Best Use Case Multi-threaded applications Single-threaded applications

Use StringBuffer when multiple threads modify the same text data.


18. Difference Between String and StringBuffer

Feature String StringBuffer
Mutability Immutable Mutable
Object Creation Creates new objects Modifies same object
Performance Slower for repeated changes Faster for repeated changes
Thread Safety Safe because immutable Thread-safe using synchronization

19. Performance Comparison

StringBuffer performs better than String during repeated modifications.

However, StringBuilder is usually faster than StringBuffer because it avoids synchronization overhead.


19.1 Slow String Concatenation

public class Main {
    public static void main(String[] args) {

        String text = "";

        for(int i = 1; i <= 5; i++) {
            text = text + i;
        }

        System.out.println(text);
    }
}

This approach creates many temporary String objects.


19.2 Better Performance Using StringBuffer

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        for(int i = 1; i <= 5; i++) {
            buffer.append(i);
        }

        System.out.println(buffer);
    }
}

The same object is modified repeatedly, which improves performance.


Synchronization makes StringBuffer slightly slower than StringBuilder.


20. Common Beginner Mistakes


20.1 Confusing length() and capacity()

length() returns character count, while capacity() returns storage size.


public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        System.out.println(buffer.length());
        System.out.println(buffer.capacity());
    }
}

Both methods return different values because they represent different concepts.


20.2 Using Invalid Index Values

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        buffer.charAt(10);
    }
}

This code throws StringIndexOutOfBoundsException because the index does not exist.


20.3 Forgetting to Convert into String

Some methods or APIs require a String object instead of StringBuffer.


public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Java");

        String text = buffer.toString();

        System.out.println(text);
    }
}

The toString() method converts mutable text into a String object.


21. Edge Cases in StringBuffer


21.1 Empty StringBuffer

public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        System.out.println(buffer.length());
    }
}

The output is 0 because no characters are stored.


21.2 Large Dynamic Data

StringBuffer efficiently handles large amounts of changing text data.


public class Main {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer();

        for(int i = 1; i <= 1000; i++) {
            buffer.append(i);
        }

        System.out.println(buffer.length());
    }
}

The internal capacity grows automatically as more data is added.


22. Important Points to Remember

  • a. StringBuffer is mutable
  • b. It supports thread-safe operations
  • c. Synchronization provides safety
  • d. append() adds text at the end
  • e. insert() adds text at a specific position
  • f. reverse() reverses character sequences
  • g. capacity() and length() are different
  • h. StringBuilder is faster but not thread-safe

The Java StringBuffer class is useful for applications that require mutable text operations with thread safety. Because it modifies the same object internally and uses synchronization for safe concurrent access, it is suitable for multi-threaded environments where shared text data must be modified securely.

Post a Comment

0Comments
Post a Comment (0)