Table of contents
1.
Introduction
2.
What is a StringBuilder in Java?
2.1.
StringBuilder class syntax
3.
Constructors of StringBuilder in Java
3.1.
StringBuilder()
3.2.
StringBuilder(CharSequence seq)
3.3.
StringBuilder(int capacity)
3.4.
StringBuilder(String str)
4.
Methods of StringBuilder in Java
5.
Java StringBuilder Examples
6.
Features of StringBuilder Class in Java
7.
Frequently Asked Questions
7.1.
Why is StringBuilder mutable in Java?
7.2.
Why is StringBuilder faster?
7.3.
What are the benefits of StringBuilder in Java?
8.
Conclusion 
Last Updated: Oct 7, 2024

StringBuilder Class in Java

Author Yashesvinee V
0 upvote

Introduction

Strings are a sequence of characters enclosed within double quotes. The String class in Java is used to create an immutable sequence of characters, i.e. the string cannot be altered within the same string object. If we try to modify the string, a new String object is created, and the new value is updated.

StringBuilder Class in Java

The StringBuilder class in Java overcomes the limitations of the String class by creating a sequence of mutable characters. This allows the modification of a string within the existing object and does not require creating a new one. StringBuilder is a very important concept of Java.

What is a StringBuilder in Java?

In Java, a StringBuilder is a mutable sequence of characters. It's part of the Java Standard Library and is found in the java.lang package. Unlike the String class, which creates immutable objects, StringBuilder allows modifications to strings without generating a new object each time. This makes it highly efficient for operations where a string needs frequent alterations, such as in loops or when constructing complex strings dynamically.

The primary advantage of using StringBuilder is its performance. Since it doesn't create a new underlying string with every modification, it consumes less memory and executes operations faster than using regular strings in scenarios requiring extensive string manipulation.

StringBuilder class syntax

Class Signature:

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence

 

Creation of instances:

StringBuilder object_name = new StringBuilder();

 

You can also read about the topic of Java Destructor, and Duck Number in Java.

Constructors of StringBuilder in Java

Here's the table with a line added before it and the description in the table:

ConstructorDescription
StringBuilder()Constructs a string builder with no characters in it and an initial capacity of 16 characters.
StringBuilder(CharSequence seq)Constructs a string builder that contains the same characters as the specified CharSequence. The initial capacity of the string builder is 16 plus the length of the CharSequence argument. If the length of the CharSequence argument is less than or equal to zero, then an IllegalArgumentException is thrown.
StringBuilder(int capacity)Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. If the capacity argument is less than or equal to zero, then an IllegalArgumentException is thrown.
StringBuilder(String str)Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.

StringBuilder()

It constructs a string builder with no characters but an initial capacity of 16 characters by default.

StringBuilder object_name = new StringBuilder();


Try this code by yourself on Online Java Compiler.
 

StringBuilder(CharSequence seq)

CharSequence is an interface that provides read-only access to different types of character sequences. In simple words, it is a readable sequence of char values.
The constructor creates a string builder containing the same characters as the specified CharSequence.

StringBuilder object_name = new StringBuilder(“aabbcc”);

 

StringBuilder(int capacity)

It constructs a string builder with no characters but a specified capacity to hold characters.

StringBuilder object_name = new StringBuilder(10);

 

StringBuilder(String str)

It constructs a string builder initialized with the characters of the given string.
 

StringBuilder object_name = new StringBuilder(“hello”);

Methods of StringBuilder in Java

Method

Parameter

Type 

Description 

append()boolean bStringBuilderIt appends the string representation of the boolean argument to the sequence.
char cIt appends the string representation of the char argument to the sequence.
char[ ] strIt appends the string representation of the char array argument to the sequence.
char[ ] str, int offset, int lenIt appends the string representation of a subarray of the char array argument to the sequence.
CharSequence sIt appends CharSequence to the sequence.
CharSequence s, int start, int endIt appends a subsequence of the specified CharSequence to the sequence.
double dIt appends the string representation of the double argument to the sequence.
float fIt appends the string representation of the float argument to the sequence.
int iIt appends the string representation of the int argument to the sequence.
long lngIt appends the string representation of the long argument to the sequence.
Object objIt appends the string representation of the object argument to the sequence.
String strIt appends the specified string to the sequence.
StringBuffer sbIt appends the specified StringBuffer to the sequence.
appendCodePoint()int codePointStringBuilderIt appends the string representation of the codePoint argument to the sequence.
capacity()-int It returns the current capacity.
charAt()int indexcharIt returns the character present at the specified index.
codePointAt()int indexintIt returns Unicode code points at the specified index in the sequence.
codePointBefore()It returns the Unicode code point before a specified index in the sequence.
codePointCount()int beginIndex, int endIndexintIt returns the number of Unicode code points in the specified range of the sequence.
delete()int start, int endStringBuilderIt removes the set of characters under a given range in the sequence.
deleteCharAt()int indexStringBuiderIt removes the character at the given index.
ensureCapacity()int minimumCapacityvoidIt ensures that the capacity is at least equal to the given minimum value.
getChars()int srcBegin,  int srcEnd, char[ ] dst, int dstBeginvoidIt copies a set of characters from a given range in the sequence to a destination char array.
indexOf()String strintIt returns the index of the first occurrence of the given string in the sequence.
String str, int fromIndexIt returns the index of the first occurrence of the given string in the sequence from a specified index.
insert()int offset, boolean bStringBuilderIt inserts the string representation of the specified boolean argument into the sequence.
int offset, char cIt inserts the string representation of the specified char argument into the sequence.
int offset, char[ ] strIt inserts the string representation of a char array argument into the sequence.
int index, char[ ] str, int offset, int lenIt inserts the string representation of a subarray of the str array argument into the sequence.
int dstOffset, CharSequence sIt inserts the specified CharSequence into the sequence.
int dstOffset, CharSequence s, int start, int endIt inserts a subsequence of the specified CharSequence into the sequence.
int offset, double dIt inserts the string representation of the specified double argument into the sequence.
int offset, float fIt inserts the string representation of the specified float argument into the sequence.
int offset, int iIt inserts the string representation of the specified int argument into the sequence.
int offset, long lngIt inserts the string representation of the specified long argument into the sequence.
int offset, Object objIt inserts the string representation of the specified object argument into the sequence.
int offset, String strIt inserts the given string into the sequence.
lastIndexOf()String strintIt returns the index of the last occurrence of the given substring in the sequence.
String str, int fromIndexIt returns the index of the last occurrence of the given substring from the specified index in the sequence.
length()-intIt returns the length of the sequence.
replace()int start, int end, String strStringBuilderIt replaces the characters in a given range in the sequence with the specified string.
reverse()-StringBuilderIt replaces the current character sequence with its reverse.
setChatAt()int index, char chvoidCharacter ch is placed at the specified index.
setLength()int newLengthvoidIt sets the length of the character sequence.
subSequence()int start, int endCharSequenceIt returns a new character sequence from a given range in the sequence.
substring()int startStringIt returns a new string of characters present from the specified index to the end of the sequence.
int start, int endIt returns a new string of characters present within the given range from the sequence.
toString()-StringIt returns a string format of the data in the sequence.
trimToSize()-voidIt tries to reduce the storage space used for the character sequence.

Also see, Hashcode Method in Java and Swap Function in Java

Java StringBuilder Examples

The insert() and append() methods, as mentioned before, perform the two main operations of inserting and appending characters to a given sequence. Let us see the methods of the StringBuilder class in action with the help of this example.

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

public class Main 
{
  public static void main(String[] args) throws Exception
  {
    StringBuilder str = new StringBuilder("ABC");

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

    str.append("D");
    System.out.println("\nAppending D => "+ str.toString());
    str.append("EFG",0,2);
    System.out.println("Appending EF => "+ str.toString());
    str.append(26);
    System.out.println("Appending 26 => "+ str.toString());

    System.out.println("\nCharacter at index 4 = "+ str.charAt(4));
    StringBuilder reverseStr = str.reverse();
    System.out.println("\nReverse String => "+ reverseStr.toString());

    str.insert(2,"GHI");
    System.out.println("\nInsertion => "+ str.toString());

    System.out.println("\nLength of the String => "+ str.length());

    System.out.println("\nSubString => "+ str.substring(2,6));

    str.replace(4,5,"G");
    System.out.println("\nReplacing I with G => "+ str.toString());

    System.out.println("\nIndex of G in the String = "+ str.indexOf("G"));
    System.out.println("Last index of G in the String = "+ str.lastIndexOf("G"));

    str.delete(4,6);
    System.out.println("\nAfter deleting \'GF\' from the String = "+ str.toString());

    str.appendCodePoint(48);
    System.out.println("\nAppending code point => "+ str);

    int capacity = str.capacity();
    System.out.println("\nCapacity of StringBuilder => "+ capacity);
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

String = ABC

Appending D => ABCD
Appending EF => ABCDEF
Appending 26 => ABCDEF26

Character at index 4 = E

Reverse String => 62FEDCBA

Insertion => 62GHIFEDCBA

Length of the String => 11

SubString => GHIF

Replacing I with G => 62GHGFEDCBA

Index of G in the String = 2
Last index of G in the String = 4

After deleting 'GF' from the String = 62GHEDCBA

Appending code point => 62GHEDCBA0

Capacity of StringBuilder => 19

Check out this problem - Longest Subarray With Sum K 

Must Read: Java System Out Println

Features of StringBuilder Class in Java

  • The StringBuilder class is very much similar to the StringBuffer class, the only difference being that the former provides no guarantee of synchronization. Hence, it is used only by single threads.
     
  • ‘Insert’ and ‘append’ are the principal methods of the StringBuilder class that are overloaded to accept values of any type.
     
  • Every string builder has a character capacity that will create a new internal buffer to accommodate more characters upon exceeding.
     
  • Passing a null value to StringBuilder’s constructors or methods results in NullPointerException.

Frequently Asked Questions

Why is StringBuilder mutable in Java?

StringBuilder is mutable to allow for modifications without creating new objects, enhancing performance during repetitive string manipulation tasks.

Why is StringBuilder faster?

StringBuilder is faster because it avoids the overhead of creating new string objects with each modification, reducing memory usage and processing time.

What are the benefits of StringBuilder in Java?

The benefits of StringBuilder in Java include improved performance for string manipulation, reduced memory overhead, and the ability to modify strings directly.

Conclusion 

String Manipulation is an important part of almost every application or program. Classes like String and StringBuilder enable programmers to deal with string values or data efficiently. This blog explains the StringBuilder class in Java and its features. It also lists the different functions and methods offered by the class and shows how to implement them.

Recommended problems:

 

You can also check out our other blogs on Code360.

Live masterclass