Master the StringBuilder Class in Java

Up to this point, we’ve discovered that a String object is immutable, which implies that its contents cannot be altered once it is created. When we perform operations on a String, a new String object is generated. In order to modify the contents of a String, we can use the StringBuilder class provided by the java.lang package.

Additionally, it may be worthwhile to examine the StringBuffer class and compare it to the StringBuilder class to identify the differences.

What is the StringBuilder class in Java?

In Java, the String class is used to represent text strings. However, one of the main limitations of the String class is that it is immutable, meaning that once a String object is created, its contents cannot be changed. This can be a problem in certain situations, such as when you need to build a string by appending or inserting characters. Consider the following example:

public class StringExample {
    public static void main(String[] args) {
        String hello = "Hello";
        String world = new String("world");
        
        // concatenate the strings
        String greeting = hello + ", " + world + "!";
        
        // print the result
        System.out.println(greeting);
    }
}

This example creates two String objects, one using a string literal ("Hello") and the other using the new keyword to create a new String object. It then concatenates these strings using the + operator, and stores the result in a new String object called greeting. Finally, the greeting string is printed to the console.

The output of this example would be:

Hello, world!

Keep in mind that because String objects are immutable, every time a modification is made to a string, a new String object must be created. This can be inefficient in situations where strings are being modified frequently.

To address this limitation, Java provides the StringBuilder class, which is a mutable alternative to the String class. The StringBuilder class allows you to build and modify strings by appending, inserting, replacing, or deleting characters, without creating new objects for each modification.

Using a mutable class like StringBuilder can be more efficient than using immutable String objects, because it avoids the need to create new objects and copy the contents of existing objects every time a modification is made. This can be especially important when dealing with large strings or performance-critical applications.

In addition to its mutability, the StringBuilder class provides a number of useful methods for working with strings, such as append, insert, replace, delete, and reverse. These methods allow you to modify strings in a variety of ways, giving you more flexibility and control over your text data.

Overall, the StringBuilder class is a powerful tool for working with text strings in Java, offering improved performance and greater flexibility compared to the immutable String class.

Internal Working of StringBuilder in Java

The StringBuilder class is designed to be a more efficient way to build and manipulate strings in Java, particularly in situations where strings are being modified frequently. One of the main reasons for its improved efficiency is its internal working mechanism.

When you create a new StringBuilder object, it allocates an initial capacity to hold the characters of the string you want to build. By default, this initial capacity is 16 characters, but you can also specify a custom initial capacity using the StringBuilder(int capacity) constructor.

As you append or insert characters into the StringBuilder object, it keeps track of the current length of the string and the available capacity. If the current length of the string plus the length of the characters being appended or inserted is greater than the available capacity, the StringBuilder object automatically increases its capacity to accommodate the new characters.

This dynamic allocation of capacity is much more efficient than creating new String objects every time a modification is made to a string, as it reduces the number of objects that need to be created and reduces memory overhead.

Another advantage of the StringBuilder class is that it allows you to modify the string in place, rather than creating a new String object every time a modification is made. This is because the StringBuilder class stores the characters of the string in a character array, which can be directly modified.

Overall, the StringBuilder class is an efficient and flexible way to build and manipulate strings in Java, thanks to its dynamic allocation of capacity and ability to modify strings in place.

Class Declaration of StringBuilder

The StringBuilder class in Java is defined in the java.lang package and has the following class declaration:

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence

 

Interfaces implemented by the StringBuilder class

This declaration indicates that the StringBuilder class is a final class, meaning that it cannot be extended by other classes. It extends the Object class, which is the root of the Java class hierarchy, and implements the Serializable, CharSequence interfaces.

The Serializable interface allows objects of the StringBuilder class to be serialized and deserialized, meaning that they can be converted into a byte stream and transmitted over a network or saved to a file. The CharSequence interface defines methods for accessing a sequence of characters, which is the primary purpose of the StringBuilder class.

Because the StringBuilder class is final and cannot be extended, it provides a consistent and predictable interface for manipulating strings in Java. This makes it a powerful tool for building and modifying strings in a variety of applications.

Constructors in Java StringBuilder Class

The StringBuilder class in Java provides several constructors for creating new StringBuilder objects. Here are the constructors available in the StringBuilder class:

  • StringBuilder()
    StringBuilder sb = new StringBuilder();
    

    This constructor creates a new StringBuilder object with an initial capacity of 16 characters. This means that the StringBuilder object can hold up to 16 characters initially before it needs to resize itself to accommodate more characters. This can be useful if you don’t know how many characters you’ll need to store in the StringBuilder object upfront, but you want to start building the string immediately.

    In the example code, we create a new StringBuilder object using this constructor and assign it to the variable sb. Since we haven’t provided any initial string or capacity values, the StringBuilder object will have an initial capacity of 16 characters.

  • StringBuilder(int capacity)
    int initialCapacity = 32;
    StringBuilder sb = new StringBuilder(initialCapacity);
    

    This constructor creates a new StringBuilder object with a custom initial capacity specified by the capacity parameter. This can be useful if you have an idea of how many characters you’ll need to store in the StringBuilder object upfront and want to allocate enough memory for them at the outset.

    In the sample code provided, we create a new StringBuilder object with an initial capacity of 32 characters and assign it to the variable sb. We’ve provided the initial capacity of 32 as an argument to the constructor.

  • StringBuilder(CharSequence seq)
    CharSequence charSeq = "Hello, world!";
    StringBuilder sb = new StringBuilder(charSeq);
    

    This constructor creates a new StringBuilder object with the same characters as the specified CharSequence object. A CharSequence is a sequence of characters that can be read, but not necessarily modified. Examples of CharSequence objects include String objects and StringBuilder objects.

    As demonstrated in the code snippet above, we create a new CharSequence object containing the string “Hello, world!” and assign it to the variable charSeq. We then create a new StringBuilder object with the same characters as charSeq and assign it to the variable sb. The initial capacity of the StringBuilder object will be set to the length of charSeq plus 16.

  • StringBuilder(String str)
    String str = "Hello, world!";
    StringBuilder sb = new StringBuilder(str);
    

    This constructor creates a new StringBuilder object with the same characters as the specified String object. This can be useful if you have an existing String object that you want to modify using the StringBuilder class.

    For the code sample provided, we create a new String object containing the string “Hello, world!” and assign it to the variable str. We then create a new StringBuilder object with the same characters as str and assign it to the variable sb. The initial capacity of the StringBuilder object will be set to the length of str plus 16.

All of these constructors create new StringBuilder objects, but with different initial capacities and source strings. The StringBuilder(CharSequence seq) and StringBuilder(String str) constructors are particularly useful for creating new StringBuilder objects that contain the same characters as an existing CharSequence or String object.

StringBuilder Length and Capacity

In Java, the length of a StringBuilder can be retrieved using the length() method. The length of a StringBuilder represents the number of characters currently stored in the buffer. The capacity of a StringBuilder is the amount of space currently allocated for the buffer. The capacity of a StringBuilder can be retrieved using the capacity() method.

When a StringBuilder is created, it has an initial capacity of 16 characters. As characters are added to the StringBuilder, its capacity automatically increases to accommodate the new characters. The amount by which the capacity increases is determined by the implementation of the StringBuilder class.

If you know that you will be appending a large number of characters to a StringBuilder, you can use the ensureCapacity() method to increase the capacity of the StringBuilder in advance. This can be useful to avoid the performance overhead of having to repeatedly increase the capacity of the StringBuilder as characters are added.

Here’s an example that demonstrates how to retrieve the length and capacity of a StringBuilder:

StringBuilder sb = new StringBuilder("Hello, world!");

// Get the length of the StringBuilder
int length = sb.length();
System.out.println("Length: " + length);

// Get the capacity of the StringBuilder
int capacity = sb.capacity();
System.out.println("Capacity: " + capacity);

StringBuilder class length and capacity

In this example, as you may have guessed, the output will be:

Length: 13
Capacity: 16

Since the StringBuilder was created with a string of length 13, the length of the StringBuilder is 13. The initial capacity of the StringBuilder is 16, so the capacity of the StringBuilder is 16.

The Benefits of StringBuilder

The StringBuilder class provides several benefits over using a regular String in Java. Here are some of the key benefits:

Mutable

One of the main benefits of StringBuilder is that it is mutable, which means that you can modify the contents of the StringBuilder object after it has been created. This is in contrast to a regular String object, which is immutable, meaning that you cannot change its value once it has been created. The ability to modify the contents of a StringBuilder object can be particularly useful in situations where you need to build up a large string gradually, such as when constructing a long message or concatenating multiple strings.

Efficient

Another benefit of StringBuilder is that it is designed to be more efficient than using regular strings for concatenation operations. When you concatenate strings using the + operator, for example, a new string is created each time, which can be quite inefficient for large strings. In contrast, StringBuilder is designed to efficiently build up a string by allocating a buffer of a certain size and dynamically increasing its size as needed.

Versatile

StringBuilder provides a wide range of methods for modifying and manipulating strings. These methods include append(), insert(), replace(), delete(), reverse(), and more. This makes StringBuilder a versatile tool for working with strings in Java.

Overall, the StringBuilder class provides several benefits over using regular strings for building and manipulating strings in Java. It is mutable, efficient, versatile, and easy to use, making it a valuable tool for developers who need to work with strings in their Java applications.

StringBuilder class with examples

StringBuilder append(String s)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java ");
        sb.append("Programming"); // original string is changed
        System.out.println(sb);
    }
}

Output:

Java Programming

The code block provided is a Java program that demonstrates the use of the StringBuilder class to modify a string. The program creates a new StringBuilder object with the initial value “Java “, and then appends the string “Programming” to the end of it using the append() method.

StringBuilder insert(int offset, String s)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        sb.insert(5, "alegru "); //inserts the specified string at index 5
        System.out.println(sb);
    }
}

Output:

Java alegru Programming

This is a Java code example that demonstrates how to use the insert() method of the StringBuilder class. The program creates a new StringBuilder object with the initial value “Java Programming”, and then uses the insert() method to insert the string “alegru ” at index 5.

StringBuilder replace(int startIndex, int endIndex, String str)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Programming");
        sb.replace(2, 5, "Java");
        System.out.println(sb);
    }
}

Output:

PrJavaamming

This is a Java code block that creates a new StringBuilder object with the initial value “Programming”. It then uses the replace() method to replace the characters at indices 2-4 (i.e. the characters “ogr”) with the string “Java”.

StringBuilder delete(int startIndex, int endIndex)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Programming");
        sb.delete(1,3);
        System.out.println(sb);
    }
}

Output:

Pgramming

This code creates a StringBuilder object and initializes it with the string “Programming”. It then calls the delete() method on the StringBuilder object to remove the characters at indices 1 and 2 (i.e., the second and third characters in the string).

StringBuilder reverse()

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        sb.reverse();
        System.out.println(sb);
    }
}

Output:

gnimmargorP avaJ

This code creates a StringBuilder object with the initial value of “Java Programming”. It then calls the reverse() method on the StringBuilder object, which reverses the order of the characters in the string.

int capacity()

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        // The initial capacity is 16
        System.out.println("The initial capacity is: " + sb.capacity());
        sb.append("Java");
        System.out.println("Current capacity is: " + sb.capacity()); // Capacity is still 16
        sb.append(" Programming Language"); // with this, we exceed the initial capacity and it increases according to this principle: (oldCapacity * 2) + 2
        System.out.println("Current capacity is: " + sb.capacity()); // Now current capacity is ((16 * 2) + 2) = 34
    }
}

Output:

The initial capacity is: 16 
Current capacity is: 16 
Current capacity is: 34

The code creates a StringBuilder object with an initial capacity of 16, and prints its capacity using the capacity() method. Then, the code appends the string “Java” to the StringBuilder object and prints its capacity again. Since the length of the string “Java” is less than the initial capacity, the capacity remains the same at 16. Then, the code appends the string ” Programming Language” to the StringBuilder object, which exceeds the initial capacity, causing the capacity to increase according to the formula (oldCapacity * 2) + 2. Finally, the code prints the new capacity of the StringBuilder object, which is 34.

void ensureCapacity(int minimumCapacity)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(); // Initial capacity is 16
        System.out.println("The initial capacity is: " + sb.capacity());
        sb.ensureCapacity(50);
        System.out.println("Current capacity: " + sb.capacity());
    }
}

Output:

The initial capacity is: 16 
Current capacity: 50

The code block is a Java program that creates a StringBuilder object with an initial capacity of 16 and prints the initial capacity to the console. It then uses the ensureCapacity() method to increase the capacity to 50 and prints the updated capacity to the console.

void setCharAt(int index, char c)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello World.");
        sb.setCharAt(1, 'A');
        System.out.println(sb);
    }
}

Output:

HAllo World.

This code creates a StringBuilder object with the string “Hello World.” and then modifies the character at index 1 to be ‘A’ using the setCharAt() method.

String substring(int beginIndex)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        System.out.println(sb.substring(5));
    }
}

Output:

Programming

The code block is a Java program that creates a StringBuilder object and initializes it with the string “Java Programming”. It then calls the substring() method on the StringBuilder object with the argument 5, which returns a new string that starts at index 5 of the original string.

String substring(int beginIndex, int endIndex)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        System.out.println(sb.substring(5, 12));
    }
}

Output:

Program

The code block is an example of using the StringBuilder class to create a new StringBuilder object with the string “Java Programming”, and then calling the substring() method to extract a portion of that string. Specifically, it extracts the characters from index 5 to index 12 (exclusive), which corresponds to the string “Program”.

StringBuilder delete(int start, int end)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        sb.delete(2, 8);
        System.out.println(sb);
    }
}

Output:

Jagramming

This code creates a StringBuilder object with the value “Java Programming”, and then uses the delete() method to remove the characters at indices 2 through 7.

StringBuilder deleteCharAt(int index)

class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java Programming");
        sb.deleteCharAt(4);
        System.out.println(sb);
    }
}

Output:

JavaProgramming

This is a Java program that creates a StringBuilder object containing the string “Java Programming”. It then deletes the character at index 4 (which is the space character between “Java” and “Programming”) using the deleteCharAt() method.

Conclusion

In conclusion, the StringBuilder class in Java provides a more efficient way of manipulating strings as compared to the String class, which is immutable. By allowing the modification of strings in place, StringBuilder minimizes the need for creating new string objects, leading to improved performance in memory utilization and execution time.

In this tutorial, we covered the basics of the StringBuilder class, including its constructors, methods, length and capacity, and benefits. With this knowledge, you can utilize the StringBuilder class to enhance the efficiency and functionality of your Java programs. Don’t forget to check out the Java Tutorials for Beginners page for more interesting content.

Frequently asked questions

  • Can I convert a StringBuilder object to a String object?
    Yes, you can convert a StringBuilder object to a String object using the toString() method provided by the StringBuilder class. The toString() method returns a string representing the data in the StringBuilder object.
  • Is StringBuilder thread-safe?
    No, StringBuilder is not thread-safe. If you need thread safety, you can use the StringBuffer class instead, which provides synchronized methods to ensure thread safety.
  • What is the performance impact of using StringBuilder compared to String in Java?
    Using StringBuilder can have a significant performance benefit over String concatenation in Java, especially when dealing with large amounts of data. Since String objects are immutable, concatenating multiple strings together creates a new String object every time, which can be resource-intensive. StringBuilder, on the other hand, allows for efficient string manipulation without the need for creating new objects every time. This can result in faster and more efficient code execution.
  • What is the maximum length of a StringBuilder object in Java?
    The maximum length of a StringBuilder object in Java is determined by the available memory of the system. Since a StringBuilder object is not limited to a fixed size like a traditional array, the length of the object can potentially grow to fill all available memory on the system. However, it’s important to note that attempting to create a StringBuilder object that is excessively large may cause performance issues or even result in a memory error.
  • Is StringBuilder compatible with other Java data types, such as integers or floats?
    Yes, StringBuilder can be used to append and manipulate other Java data types such as integers, floats, doubles, and characters. You can use the various append() methods provided by the StringBuilder class to append any type of data to a StringBuilder object.

Leave a Reply

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