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

Java StringBuilder Class

Last Updated : 24 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Java, StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String, which creates a new object for every modification, StringBuilder allows in-place changes, making it memory-efficient and faster for large or frequent string manipulations.

Important Points:

  • StringBuilder in Java represents a mutable sequence of characters.
  • String Class in Java creates an immutable sequence of characters, whereas StringBuilder creates a mutable sequence of characters, offering an alternative.
  • Functionality of StringBuilder is similar to the StringBuffer class, as both provide mutable sequences of characters.
  • StringBuilder does not guarantee synchronization, while StringBuffer does.
  • StringBuilder is designed as a drop-in replacement for StringBuffer in scenarios where StringBuffer is used by a single thread.
  • StringBuilder is faster than StringBuffer in most implementations.
  • StringBuilder is not thread-safe and should not be used in multi-threaded environments. If thread safety is required, it is recommended to use StringBuffer instead.
  • StringBuilder is high in performance but lacks thread-safety compared to StringBuffer.

Example: Here, you can see all Type of methods which included append(), insert(), replace(), delete(), reverse(), etc. in StringBuilder class.

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

        // Create a new StringBuilder with the
        // initial content "GeeksforGeeks"
        StringBuilder sb = new StringBuilder("GeeksforGeeks");
        System.out.println("Initial StringBuilder: " + sb);

        // 1. Append a string to the StringBuilder
        sb.append(" is awesome!");
        System.out.println("After append: " + sb);

        // 2. Insert a substring at a specific position
        sb.insert(13, " Java");
        System.out.println("After insert: " + sb);

        // 3. Replace a substring with another string
        sb.replace(0, 5, "Welcome to");
        System.out.println("After replace: " + sb);

        // 4. Delete a substring from the StringBuilder
        sb.delete(8, 14);
        System.out.println("After delete: " + sb);

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

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

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

        // 8. Access a character at a specific index
        char charAt5 = sb.charAt(5);
        System.out.println("Character at index 5: " + charAt5);

        // 9. Set a character at a specific index
        sb.setCharAt(5, 'X');
        System.out.println("After setCharAt: " + sb);

        // 10. Get a substring from the StringBuilder
        String substring = sb.substring(5, 10);
        System.out.println("Substring (5 to 10): " + substring);

        // 11. Find the index of a specific substring
        sb.reverse(); // Reversing back to original order for search
        int indexOfGeeks = sb.indexOf("Geeks");
        System.out.println("Index of 'Geeks': " + indexOfGeeks);

        // 12. Delete a character at a specific index
        sb.deleteCharAt(5);
        System.out.println("After deleteCharAt: " + sb);

        // 13. Convert the StringBuilder to a String
        String result = sb.toString();
        System.out.println("Final String: " + result);
    }
}

Output
Initial StringBuilder: GeeksforGeeks
After append: GeeksforGeeks is awesome!
After insert: GeeksforGeeks Java is awesome!
After replace: Welcome toforGeeks Java is awesome!
After delete: Welcome eeks ...

Explanation:

  • The code demonstrates the usage of multiple StringBuilder methods like append(), insert(), replace(), delete(), reverse(), etc.
  • The keyword “GeeksforGeeks” is used the operations to make the examples.

Declaration:

StringBuilder sb = new StringBuilder("Initial String");

Class Hierarchy:  

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

Syntax:  

public final class StringBuilder
extends Object
implements Serializable, CharSequence

Constructors in Java StringBuilder Class  

ConstructorDescriptionExample
StringBuilder()Creates an empty StringBuilder with a default initial capacity of 16.StringBuilder strbldr = new StringBuilder();
StringBuilder(int capacity)Creates a StringBuilder with the specified initial capacity.StringBuilder strbldr = new StringBuilder(50);
StringBuilder(String str)Creates a StringBuilder initialized with the contents of the given string.StringBuilder strbldr = new StringBuilder("Geeks");
StringBuilder(CharSequence cs)Creates a StringBuilder initialized with the contents of the given CharSequence object.CharSequence strbldr = "Geeks"; StringBuilder sb = new StringBuilder(cs);

Methods of StringBuilder class

MethodDescriptionExample
append(String str)Appends the specified string to the end of the StringBuilder.sb.append("Geeks");
insert(int offset, String)Inserts the specified string at the given position in the StringBuilder.sb.insert(5, " Geeks");
replace(int start, int end, String)Replaces characters in a substring with the specified string.sb.replace(6, 11, "Geeks");
delete(int start, int end)Removes characters in the specified range.sb.delete(5, 11);
reverse()Reverses the sequence of characters in the StringBuilder.sb.reverse();
capacity()Returns the current capacity of the StringBuilder.int cap = sb.capacity();
length()Returns the number of characters in the StringBuilder.int len = sb.length();
charAt(int index)Returns the character at the specified index.char ch = sb.charAt(4);
setCharAt(int index, char)Replaces the character at the specified position with a new character.sb.setCharAt(0, 'G');
substring(int start, int end)Returns a new String that contains characters from the specified range.String sub = sb.substring(0, 5);
ensureCapacity(int minimum)Ensures the capacity of the StringBuilder is at least equal to the specified minimum.sb.ensureCapacity(50);
deleteCharAt(int index)Removes the character at the specified position.sb.deleteCharAt(3);
indexOf(String str)Returns the index of the first occurrence of the specified string.int idx = sb.indexOf("Geeks");
lastIndexOf(String str)Returns the index of the last occurrence of the specified string.int idx = sb.lastIndexOf("Geeks");
toString()Converts the StringBuilder object to a String.String result = sb.toString();

Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

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 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 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 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
2 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
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
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
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
3 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. In Java, String, StringBuilder, and StringBuffer are used for handling strings. The main difference is:String: Immutable, meaning its value cannot be changed once created. It is thread-safe but less memory-effici
6 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