The Wayback Machine - https://web.archive.org/web/20240921095929/https://www.geeksforgeeks.org/stringbuilder-class-in-java-with-examples/
Open In App

StringBuilder Class in Java with Examples

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer class, as both of them provide an alternative to String Class by making a mutable sequence of characters. However, the StringBuilder class differs from the StringBuffer class on the basis of synchronization. The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. String Builder is not thread-safe and high in performance compared to String buffer.

The class hierarchy is as follows:  

java.lang.Object
 ↳ java.lang
    ↳ Class StringBuilder

Syntax:  

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence

Constructors in Java StringBuilder Class 

  • StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters.
  • StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
  • StringBuilder(CharSequence seq): Constructs a string builder that contains the same characters as the specified CharSequence.
  • StringBuilder(String str): Constructs a string builder initialized to the contents of the specified string. 

Below is a sample program to illustrate StringBuilder in Java. 

Java
// Java Code to illustrate StringBuilder

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        // Create a StringBuilder object
        // using StringBuilder() constructor
        StringBuilder str = new StringBuilder();

        str.append("GFG");

        // print string
        System.out.println("String = " + str.toString());

        // create a StringBuilder object
        // using StringBuilder(CharSequence) constructor
        StringBuilder str1
            = new StringBuilder("AAAABBBCCCC");

        // print string
        System.out.println("String1 = " + str1.toString());

        // create a StringBuilder object
        // using StringBuilder(capacity) constructor
        StringBuilder str2 = new StringBuilder(10);

        // print string
        System.out.println("String2 capacity = "
                           + str2.capacity());

        // create a StringBuilder object
        // using StringBuilder(String) constructor
        StringBuilder str3
            = new StringBuilder(str1.toString());

        // print string
        System.out.println("String3 = " + str3.toString());
    }
}

Output
String = GFG
String1 = AAAABBBCCCC
String2 capacity = 10
String3 = AAAABBBCCCC

Methods in Java StringBuilder

StringBuilder append(X x): This method appends the string representation of the X type argument to the sequence.

  1. StringBuilder appendCodePoint(int codePoint): This method appends the string representation of the codePoint argument to this sequence.
  2. int capacity(): This method returns the current capacity.
  3. char charAt(int index): This method returns the char value in this sequence at the specified index.
  4. IntStream chars(): This method returns a stream of int zero-extending the char values from this sequence.
  5. int codePointAt(int index): This method returns the character (Unicode code point) at the specified index.
  6. int codePointBefore(int index): This method returns the character (Unicode code point) before the specified index.
  7. int codePointCount(int beginIndex, int endIndex): This method returns the number of Unicode code points in the specified text range of this sequence.
  8. IntStream codePoints(): This method returns a stream of code point values from this sequence.
  9. StringBuilder delete(int start, int end): This method removes the characters in a substring of this sequence.
  10. StringBuilder deleteCharAt(int index): This method removes the char at the specified position in this sequence.
  11. void ensureCapacity(int minimumCapacity): This method ensures that the capacity is at least equal to the specified minimum.
  12. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method characters are copied from this sequence into the destination character array dst.
  13. int indexOf(): This method returns the index within this string of the first occurrence of the specified substring.
  14. StringBuilder insert(int offset, boolean b): This method inserts the string representation of the boolean alternate argument into this sequence.
  15. StringBuilder insert(): This method inserts the string representation of the char argument into this sequence.
  16. int lastIndexOf(): This method returns the index within this string of the last occurrence of the specified substring.
  17. int length(): This method returns the length (character count).
  18. int offsetByCodePoints(int index, int codePointOffset): This method returns the index within this sequence that is offset from the given index by codePointOffset code points.
  19. StringBuilder replace(int start, int end, String str): This method replaces the characters in a substring of this sequence with characters in the specified String.
  20. StringBuilder reverse(): This method causes this character sequence to be replaced by the reverse of the sequence.
  21. void setCharAt(int index, char ch): In this method, the character at the specified index is set to ch.
  22. void setLength(int newLength): This method sets the length of the character sequence.
  23. CharSequence subSequence(int start, int end): This method returns a new character sequence that is a subsequence of this sequence.
  24. String substring(): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
  25. String toString(): This method returns a string representing the data in this sequence.
  26. void trimToSize(): This method attempts to reduce storage used for the character sequence. 

Example:  

Java
// Java code to illustrate
// methods of StringBuilder

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {

        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("AAAABBBCCCC");

        // print string
        System.out.println("String = "
                           + str.toString());

        // reverse the string
        StringBuilder reverseStr = str.reverse();

        // print string
        System.out.println("Reverse String = "
                           + reverseStr.toString());

        // Append ', '(44) to the String
        str.appendCodePoint(44);

        // Print the modified String
        System.out.println("Modified StringBuilder = "
                           + str);

        // get capacity
        int capacity = str.capacity();

        // print the result
        System.out.println("StringBuilder = " + str);
        System.out.println("Capacity of StringBuilder = "
                           + capacity);
    }
}

Output
String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA
Modified StringBuilder = CCCCBBBAAAA,
StringBuilder = CCCCBBBAAAA,
Capacity of StringBuilder = 27

StringBuilder is another class in Java that is used to manipulate strings. Like StringBuffer, it is a mutable class that allows you to modify the contents of the string it represents. However, StringBuilder is not thread-safe, so it should not be used in a multi-threaded environment.

Here are some examples of how to use StringBuilder in Java:

Java
public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(" ");
        sb.append("world!");
        System.out.println(sb.toString()); // Output: "Hello world!"
        
        sb.insert(6, "beautiful ");
        System.out.println(sb.toString()); // Output: "Hello beautiful world!"
        
        sb.reverse();
        System.out.println(sb.toString()); // Output: "!dlrow lufituaeb olleH"
    }
}

Output
Hello world!
Hello beautiful world!
!dlrow lufituaeb olleH


Previous Article
Next Article

Similar Reads

StringBuilder charAt() in Java with Examples
The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object. The index value should lie between 0 and length()-1. Syntax: public char charAt(int index) Parameters: This method accepts one int type parameter index which represents index of the character to be
3 min read
StringBuilder codePointAt() in Java with Examples
The codePointAt(int index) method of StringBuilder class takes an index as a parameter and returns a character unicode point at that index in String contained by StringBuilder or we can say charPointAt() method returns the "unicode number" of the character at that index. The index refers to char values (Unicode code units) and the value of index mu
4 min read
StringBuilder append() Method in Java With Examples
The java.lang.StringBuilder.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used by the passing of various types of arguments: StringBuilder append(boolean a) :The java.lang.StringBuilder.append(boolean a) is an inbuilt method in Java which is
13 min read
StringBuilder delete() in Java with Examples
The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after the last character of the substring to be removed fr
3 min read
StringBuilder codePointCount() in Java with Examples
The codePointCount() method of StringBuilder class returns the number of Unicode code points in the specified text range in String contained by StringBuilder. This method takes two indexes as a parameter- first beginIndex which represents index of the first character of the text range and endIndex which represents index after the last character of
3 min read
StringBuilder capacity() in Java with Examples
The capacity() method of StringBuilder Class is used to return the current capacity of StringBUilder object. The capacity is the amount of storage available to insert new characters.Syntax: public int capacity() Return Value: This method returns the current capacity of StringBuilder Class.Below programs demonstrate the capacity() method of StringBu
2 min read
StringBuilder codePointBefore() in Java with Examples
The codePointBefore() method of StringBuilder class takes an index as a parameter and returns the "Unicode number" of the character before the specified index in String contained by StringBuilder. The index refers to char values (Unicode code units) and the value of index must lie between 0 to length-1. If the char value at (index - 1) is in the lo
2 min read
StringBuilder deleteCharAt() in Java with Examples
The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after application
3 min read
StringBuilder ensureCapacity() in Java with Examples
The ensureCapacity(int minimumCapacity) method of StringBuilder class helps us to ensures the capacity is at least equal to the specified minimumCapacity passed as the parameter to the method. If the current capacity of StringBuilder is less than the argument minimumCapacity, then a new internal array is allocated with greater capacity. If the mini
2 min read
StringBuilder getChars() in Java with Examples
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of StringBuilder class copies the characters starting at the given index:srcBegin to index:srcEnd-1 from String contained by StringBuilder into an array of char passed as parameter to function. The characters are copied from StringBuilder into the array dst[] starting at index:
3 min read
StringBuilder length() in Java with Examples
The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method. Syntax: public int length() Return Value: This method returns length of sequence of characters contained by StringBuilde
2 min read
StringBuilder offsetByCodePoints() method in Java with Examples
The offsetByCodePoints() method of StringBuilder class returns the index within this String contained by StringBuilder that is offset from the index passed as parameter by codePointOffset code points. Unpaired surrogates lies between index and codePointOffset count as one code point each. Syntax: public int offsetByCodePoints(int index, int codePoi
2 min read
StringBuilder replace() in Java with Examples
The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. At first, the
3 min read
StringBuilder setCharAt() in Java with Examples
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to
2 min read
StringBuilder reverse() in Java with Examples
The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence. Syntax: public java.lang.AbstractStringBuilder reverse() Returns: This method returns StringBuilder object after reversing the characters. Below programs illustrate
1 min read
StringBuilder setLength() in Java with Examples
The setLength(int newLength) method of StringBuilder is used to set the length of the character sequence equal to newLength.For every index k greater than 0 and less than newLength. If the newLength passed as argument is less than the old length, the old length is changed to the newLength.If the newLength passed as argument is greater than or equal
3 min read
StringBuilder subSequence() in Java with Examples
The subSequence(int start, int end) method of StringBuilder class is the inbuilt method used to return a subsequence of characters lie between index start and end-1 of this sequence. The subsequence starts with the char value at the index start and ends with the char value at (end-1). The length of the returned subsequence is end-start. So if start
3 min read
StringBuilder substring() method in Java with examples
In StringBuilder class, there are two types of substring method depending upon the parameters passed to it. substring(int start) The substring(int start) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character
3 min read
StringBuilder toString() method in Java with Examples
The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(). Subsequent changes to this sequence contained b
3 min read
StringBuilder trimToSize() method in Java with Examples
The trimToSize() method of StringBuilder class is the inbuilt method used to trims the capacity used for the character sequence of StringBuilder object. If the buffer used by StringBuilder object is larger than necessary to hold its current sequence of characters, then this method is called to resize the StringBuilder object for converting this obj
2 min read
StringBuilder appendCodePoint() method in Java with Examples
The appendCodePoint(int codePoint) method of StringBuilder class is the inbuilt method used to append the string representation of the codePoint argument to this sequence. The argument is appended to this StringBuilder content and length of the object is increased by Character.charCount(codePoint). The effect is the same as if the int value in para
2 min read
StringBuilder lastIndexOf() method in Java with Examples
In StringBuilder class, there are two types of lastIndexOf() method depending upon the parameters passed to it. lastIndexOf(String str) The lastIndexOf(String str) method of StringBuilder class is the inbuilt method used to return the index within the String for last occurrence of passed substring as parameter. The last occurrence of the empty stri
4 min read
StringBuilder indexOf() method in Java with Examples
In StringBuilder class, there are two types of indexOf() method depending upon the parameters passed to it. indexOf(String str) The indexOf(String str) method of StringBuilder class is the inbuilt method used to return the index within the String for first occurrence of passed substring as parameter. If substring str is not present then -1 is retur
4 min read
Matcher appendTail(StringBuilder) method in Java with Examples
The appendTail(StringBuilder) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and appends it to the given StringBuilder at the tail position. Syntax: public StringBuilder appendTail(StringBuilder builder) Parameters: This method takes a parameter builder which is the StringBuilder that stores the t
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters: This method takes two parameters: builde
3 min read
When to use Rope over StringBuilder in Java?
What are Ropes? Rope is a binary tree data structure where each node except the leaf contains the number of characters present to the left of the node. They are mainly used by text editors to store and manipulate large strings. It provides different string operations such as append, insert and delete in a faster and more efficient way. Ropes work m
3 min read
Difference Between StringBuffer and StringBuilder in Java
Strings in Java are the objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. However, java provides multiple classes through which strings can be used. Two such classes are StringBuffer and StringBuilder.
4 min read
String vs StringBuilder vs StringBuffer in Java
A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. Initializing a String is one of the important pillars required as a pre-requisite with deeper understanding. Comparison between String, StringBuilder, and StringBufferFeature String StringBuilder StringBuffer Int
7 min read
When to use StringJoiner over StringBuilder?
Prerequisite: StringJoinerStringJoiner is very useful, when you need to join Strings in a Stream. Task : Suppose we want the string "[George:Sally:Fred]", where we have given a string array that contains "George", "Sally" and "Fred".StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix
2 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read