StringBuilder class

The StringBuilder class in Java is a mutable sequence of characters. Unlike the String class, StringBuilder objects can be modified without creating new objects. It is similar to StringBuffer but is not synchronized, making it faster for use in single-threaded applications.

Features of StringBuilder:

  1. Mutability: Modifying a StringBuilder object does not create a new object.

  2. Performance: Faster than String for concatenation and modification.

  3. Thread Safety: Not thread-safe (unlike StringBuffer).

  4. Efficiency: Ideal for single-threaded environments where frequent string modifications are needed.

Syntax:

StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(String str);
StringBuilder sb = new StringBuilder(int capacity);Code language: JavaScript (javascript)

Methods

Method Syntax Description
append(String str) StringBuilder append(String str) Appends the specified string to this StringBuilder.
append(int i) StringBuilder append(int i) Appends the string representation of the integer to this StringBuilder.
append(char c) StringBuilder append(char c) Appends the specified character to this StringBuilder.
append(boolean b) StringBuilder append(boolean b) Appends the string representation of the boolean to this StringBuilder.
insert(int offset, String str) StringBuilder insert(int offset, String str) Inserts the specified string at the specified position.
insert(int offset, int i) StringBuilder insert(int offset, int i) Inserts the string representation of the integer at the specified position.
insert(int offset, char c) StringBuilder insert(int offset, char c) Inserts the specified character at the specified position.
replace(int start, int end, String str) StringBuilder replace(int start, int end, String str) Replaces the substring from start to end with the specified string.
delete(int start, int end) StringBuilder delete(int start, int end) Deletes the characters from start index to end index.
deleteCharAt(int index) StringBuilder deleteCharAt(int index) Deletes the character at the specified index.
reverse() StringBuilder reverse() Reverses the sequence of characters in this StringBuilder.
charAt(int index) char charAt(int index) Returns the character at the specified index.
length() int length() Returns the length of the character sequence.
capacity() int capacity() Returns the current capacity of the StringBuilder object.
ensureCapacity(int minCapacity) void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum capacity.
setLength(int newLength) void setLength(int newLength) Sets the length of the character sequence. If the new length is greater, \u0000 characters are added.
substring(int start) String substring(int start) Returns a substring from the specified start index to the end.
substring(int start, int end) String substring(int start, int end) Returns a substring from the start index to the end index.
toString() String toString() Converts the StringBuilder to a String.
indexOf(String str) int indexOf(String str) Returns the index of the first occurrence of the specified string.
indexOf(String str, int fromIndex) int indexOf(String str, int fromIndex) Returns the index of the first occurrence of the specified string starting from the given index.
lastIndexOf(String str) int lastIndexOf(String str) Returns the index of the last occurrence of the specified string.
lastIndexOf(String str, int fromIndex) int lastIndexOf(String str, int fromIndex) Returns the index of the last occurrence of the specified string starting from the given index.
setCharAt(int index, char ch) void setCharAt(int index, char ch) Sets the character at the specified index to the specified character.

Program

public class StringBuilderDemo {

    public static void main(String[] args) {

        // Initializing StringBuilder with a name
        StringBuilder sb = new StringBuilder("Mahesh");

        // 1. Append
        sb.append(" LotusJavaPrince");
        System.out.println("After Append: " + sb);

        // 2. Insert
        sb.insert(7, "Paani ");
        System.out.println("After Insert: " + sb);

        // 3. Replace
        sb.replace(0, 6, "MAHESH");
        System.out.println("After Replace: " + sb);

        // 4. Delete
        sb.delete(7, 13);
        System.out.println("After Delete: " + sb);

        // 5. Reverse
        sb.reverse();
        System.out.println("After Reverse: " + sb);

        // 6. Set Length
        sb.setLength(15);
        System.out.println("After Setting Length: " + sb);

        // 7. Insert at specific index
        sb.insert(0, "Welcome ");
        System.out.println("After Insert at 0: " + sb);

        // 8. Ensure Capacity
        sb.ensureCapacity(50);
        System.out.println("Capacity: " + sb.capacity());

        // 9. Set Character at Index
        sb.setCharAt(0, 'w');
        System.out.println("After Setting Char: " + sb);

        // 10. Substring
        String subStr = sb.substring(0, 7);
        System.out.println("Substring (0-7): " + subStr);
    }
}
/*
After Append: Mahesh LotusJavaPrince
After Insert: Mahesh Paani LotusJavaPrince
After Replace: MAHESH Paani LotusJavaPrince
After Delete: MAHESH LotusJavaPrince
After Reverse: ecnirPavaJsutoL HSEHAM
After Setting Length: ecnirPavaJsutoL
After Insert at 0: Welcome ecnirPavaJsutoL
Capacity: 50
After Setting Char: welcome ecnirPavaJsutoL
Substring (0-7): welcome
*/

The StringBuilder class in Java is an essential utility for efficiently handling and manipulating mutable sequences of characters. Unlike the String class, which is immutable and creates a new object each time it is modified, StringBuilder allows modifications to be made to the same object without creating new instances, which leads to better performance, particularly in scenarios where strings need frequent updates, such as in loops or concatenation operations.

Here are the key takeaways regarding StringBuilder:

  1. Mutability: StringBuilder objects are mutable, meaning they can be modified after their creation without creating new objects, which makes it more memory-efficient compared to String.

  2. Performance: Since it does not create a new object every time a string is modified, it performs better than String when there are frequent changes to the string content, especially in large-scale operations or within loops.

  3. Methods: StringBuilder comes with several powerful methods like append(), insert(), replace(), delete(), and reverse(), which allow manipulation of the content in various ways. It also offers methods to modify the string length and capacity, such as setLength() and ensureCapacity(), giving developers fine control over memory management.

  4. Thread Safety: One limitation to keep in mind is that StringBuilder is not thread-safe. If multiple threads need to modify the same StringBuilder instance concurrently, synchronization mechanisms should be used, or an alternative like StringBuffer (which is thread-safe) should be considered.

  5. When to Use: StringBuilder should be used when the performance of string manipulations is crucial, especially for tasks like constructing dynamic strings, appending to strings, or performing frequent updates. For simple, immutable strings or when thread safety is required, String or StringBuffer might be more suitable.

StringBuilder is a highly effective and performance-oriented class for handling mutable strings in Java. By understanding its methods and performance benefits, developers can optimize their string handling for applications where string content is constantly changing.

Leave a Comment

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

Scroll to Top