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.
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
Here's the table with a line added before it and the description in the table:
Constructor
Description
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.
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 b
StringBuilder
It appends the string representation of the boolean argument to the sequence.
char c
It appends the string representation of the char argument to the sequence.
char[ ] str
It appends the string representation of the char array argument to the sequence.
char[ ] str, int offset, int len
It appends the string representation of a subarray of the char array argument to the sequence.
CharSequence s
It appends CharSequence to the sequence.
CharSequence s, int start, int end
It appends a subsequence of the specified CharSequence to the sequence.
double d
It appends the string representation of the double argument to the sequence.
float f
It appends the string representation of the float argument to the sequence.
int i
It appends the string representation of the int argument to the sequence.
long lng
It appends the string representation of the long argument to the sequence.
Object obj
It appends the string representation of the object argument to the sequence.
String str
It appends the specified string to the sequence.
StringBuffer sb
It appends the specified StringBuffer to the sequence.
appendCodePoint()
int codePoint
StringBuilder
It appends the string representation of the codePoint argument to the sequence.
capacity()
-
int
It returns the current capacity.
charAt()
int index
char
It returns the character present at the specified index.
codePointAt()
int index
int
It 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 endIndex
int
It returns the number of Unicode code points in the specified range of the sequence.
delete()
int start, int end
StringBuilder
It removes the set of characters under a given range in the sequence.
deleteCharAt()
int index
StringBuider
It removes the character at the given index.
ensureCapacity()
int minimumCapacity
void
It ensures that the capacity is at least equal to the given minimum value.
getChars()
int srcBegin, int srcEnd, char[ ] dst, int dstBegin
void
It copies a set of characters from a given range in the sequence to a destination char array.
indexOf()
String str
int
It returns the index of the first occurrence of the given string in the sequence.
String str, int fromIndex
It returns the index of the first occurrence of the given string in the sequence from a specified index.
insert()
int offset, boolean b
StringBuilder
It inserts the string representation of the specified boolean argument into the sequence.
int offset, char c
It inserts the string representation of the specified char argument into the sequence.
int offset, char[ ] str
It inserts the string representation of a char array argument into the sequence.
int index, char[ ] str, int offset, int len
It inserts the string representation of a subarray of the str array argument into the sequence.
int dstOffset, CharSequence s
It inserts the specified CharSequence into the sequence.
int dstOffset, CharSequence s, int start, int end
It inserts a subsequence of the specified CharSequence into the sequence.
int offset, double d
It inserts the string representation of the specified double argument into the sequence.
int offset, float f
It inserts the string representation of the specified float argument into the sequence.
int offset, int i
It inserts the string representation of the specified int argument into the sequence.
int offset, long lng
It inserts the string representation of the specified long argument into the sequence.
int offset, Object obj
It inserts the string representation of the specified object argument into the sequence.
int offset, String str
It inserts the given string into the sequence.
lastIndexOf()
String str
int
It returns the index of the last occurrence of the given substring in the sequence.
String str, int fromIndex
It returns the index of the last occurrence of the given substring from the specified index in the sequence.
length()
-
int
It returns the length of the sequence.
replace()
int start, int end, String str
StringBuilder
It replaces the characters in a given range in the sequence with the specified string.
reverse()
-
StringBuilder
It replaces the current character sequence with its reverse.
setChatAt()
int index, char ch
void
Character ch is placed at the specified index.
setLength()
int newLength
void
It sets the length of the character sequence.
subSequence()
int start, int end
CharSequence
It returns a new character sequence from a given range in the sequence.
substring()
int start
String
It returns a new string of characters present from the specified index to the end of the sequence.
int start, int end
It returns a new string of characters present within the given range from the sequence.
toString()
-
String
It returns a string format of the data in the sequence.
trimToSize()
-
void
It tries to reduce the storage space used for the character sequence.
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
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
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.