Java StringBuilder class represents a mutable sequence of characters (string). That is, we can change (or modify) the content of StringBuilder, without creating a new StringBuilder object.
In other simple words, we can add or delete a new content into StringBuilder object, without creating a new StringBuilder object.
Whereas in the case of String, a string object is immutable. Once created, string object cannot change or modify. That is, the value of string object is fixed once the string is constructed.
StringBuilder class was introduced in Java 5. It is present in java.lang.StringBuilder package and automatically imported into every java program.
Why do we need StringBuilder in Java?
StringBuffer and StringBuilder both represent a mutable sequence of characters. We can change the content of StringBuffer and StringBuilder without constructing a new object.
In Java, StringBuilder class is identical to StringBuffer class except one important difference:
StringBuffer is thread-safe and StringBuilder is not thread-safe. Methods provided by StringBuffer for modifying the buffer are synchronized, which means that only one thread is allowed to access StringBuffer object at a time.
Most of the time, we do not require thread safety. In such as case, if we use StringBuffer, the performance of the application will be down. Performance wise, string buffer is not recommended to use.
This is the reason that StringBuilder class was added later in J2SE 5. The main advantage of using StringBuilder is faster performance because multiple threads have not to wait to access the same string builder object at a time. That’s why, performance is relatively high.
Note: In StringBuffer and StringBuilder, almost everything is the same, including constructors and methods.
Syntax of StringBuilder Class
Java StringBuilder class inherits from the Object class and implements Serializable and CharSequence interfaces. The general syntax to define StringBuilder class in Java is as follows:
public final class StringBuilder extends Object implements Serializable, CharSequence
Constructors of StringBuilder class
The StringBuilder class contains four constructors in Java. They are as follows:
1. StringBuilder(): This no-args constructors creates an empty String Builder with the initial default capacity of 16.
The syntax to create a StringBuilder object in Java is as follows:
StringBuilder sb = new StringBuilder(); // Initial capacity 16 characters.
2. StringBuilder(String str): This form of constructor creates a String Builder with the specified string. The syntax to create an instance of StringBuilder class with the specified string is as:
StringBuilder sb = new StringBuilder(String str); For example: StringBuilder sb = new StringBuilder("Hello World!"); // initializes sb to "Hello World!"
3. StringBuilder(int length): This form of constructor constructs an empty String Builder with the specified capacity as length.
The syntax to construct an instance of StringBuilder class with the specified capacity is as follows:
StringBuilder sb = new StringBuilder(int length); For example: StringBuilder sb = new StringBuilder(30); // initial capacity 40.
4. StringBuilder(CharSequence cs): This form of constructor creates a StringBuilder object, whose content is the same as the specified CharSequence. It takes CharSequence object as an argument.
The syntax to create a StringBuilder with specified CharSequence is as:
StringBuilder sb = new StringBuilder(CharSequence cs);
StringBuilder Methods in Java
In addition to the inherited methods from the Object class and CharSequence, methods provided by StringBuilder class are almost similar to methods of StringBuffer class.
Here, we will discuss some important StringBuilder class’s methods with various example programs. So, let’s see one by one.
1. append():
The append() method of StringBuilder class concatenates the string representation of any other data type to the end of the invoking StringBuffer object. It has several overloaded versions. A few of them are as follows:
- StringBuilder append(char c)
- StringBuilder append(String s)
- StringBuilder append(int i)
- StringBuilder append(long l)
- StringBuilder append(float f)
- StringBuffer append(Object obj)
Let’s take an example program based on append() method.
Program code:
public class AppendDemo { public static void main(String[] args) { String s; StringBuilder sb = new StringBuilder("Hello "); StringBuilder sb2 = sb.append("Java"); // Original string is changed. System.out.println("New string: " +sb2); int x = 8; s = sb.append(" ").append(x).append("!").toString(); System.out.println(s); } }
Output: New string: Hello Java Hello Java 8!
2. insert():
The insert() method inserts a string representation of all simple data types plus String, Object, and CharSequence into the invoking StringBuilder object. It has numerous overloaded version. A few of them are as follows:
- StringBuilder insert(int index, boolean b)
- StringBuilder insert(int index, char ch)
- StringBuilder insert(int index, int i)
- StringBuilder insert(int index, long l)
- StringBuilder insert(int index, float f)
- StringBuilder insert(int index, String str)
- StringBuilder insert(int index, Object obj)
Let’s create a simple program in which we will insert a string to the invoking StringBuilder object.
Program code:
public class InsertDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder(30); StringBuilder sb1 = sb.append("I love you "); StringBuilder sb2 = sb1.insert(2, "really "); StringBuilder sb3 = sb2.insert(18, "so much"); System.out.println(sb3); } }
Output: I really love you so much
3. replace():
The replace() method replaces one set of characters with another set inside a StringBuilder object. Its signature is given here:
StringBuilder replace(int startIndex, int endIndex, String s)
Here, startIndex and endIndex specifies the substring being replaced. Thus, the substring is replaced from startIndex to endIndex – 1.
Let’s take a simple program based on the replace() method.
Program code:
public class ReplaceDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("I love you"); System.out.println("Original StringBuilder: " +sb); StringBuilder sb1 = sb.replace(2, 6, "like"); System.out.println("New StringBuilder: " +sb1); } }
Output: Original StringBuilder: I love you New StringBuilder: I like you
4. delete():
This method delete the sequence of characters or string from the specified startIndex to endIndex within a StringBuilder object. It has the following syntax:
StringBuilder delete(int startIndex, int endIndex)
5. deleteCharAt():
The deleteCharAt( ) method deletes the character at the specified index. It returns the resulting StringBuilder object. The general syntax to define this method is as follows:
StringBuilder deleteCharAt(int index)
Let’s take an example program where we will delete the sequence of characters within StringBuilder object.
Program code:
public class DeleteDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Java Programming Language"); System.out.println("Original StringBuilder: " +sb); StringBuilder sb2 = sb.delete(5, 17); System.out.println("After delete operation: " +sb2); StringBuilder sb3 = sb2.deleteCharAt(6); System.out.println("After deleteCharAt operation: " +sb3); } }
Output: Original StringBuilder: Java Programming Language After delete operation: Java Language After deleteCharAt operation: Java Lnguage
6. reverse():
The reverse() method of StringBuilder class reverses the current string or sequence of characters within a StringBuffer object. It returns the reversed object on which it was called. The general syntax to define this method is as:
StringBuilder reverse()
Let’s create a program in which we will reverse characters in StringBuilder object using reverse() method.
Program code:
public class ReverseDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abcdefghi"); System.out.println("Original StringBuilder: " +sb); StringBuilder sb2 = sb.reverse(); System.out.println("Reversed StringBuilder: " +sb2); } }
Output: Original StringBuilder: abcdefghi Reversed StringBuilder: ihgfedcba
7. length():
The length() method returns the current length of a StringBuilder object. In other words, this method returns the number of characters actually stored in the string builder object. The general form of length() method is as:
public int length()
8. setLength():
This method sets the length of StringBuilder object. Its general form of this method is shown here:
public void setLength(int newLength)
If the newLength argument is less than the current length of the string builder object, the StringBuilder truncates exactly the number of characters beyond the new length.
If the newLength argument is greater than or equal to the current length, null characters are added to the existing string builder so that length becomes the newLength argument. The newLength argument must be greater than or equal to zero.
9. capacity():
This method returns the current capacity of the string builder. The capacity is the ability to store the number of characters within the string builder without increasing its size. The general form of the capacity() method is shown below:
public int capacity()
10. ensureCapacity():
The ensureCapacity() method provided by StringBuilder class ensures that the capacity is at least equal to the specified minimum capacity ‘mc’. The general syntax to define this method is as:
public void ensureCapacity(int mc); // Here, mc is the minimum capacity.
a) If the current capacity is less than specified minimum capacity ‘mc’, a new internal array allocates with the greater capacity. The new capacity is larger of minimum capacity and sum of twice the old capacity plus 2. For example, if the current capacity is 18, it will be (18 * 2) + 2 = 38.
b) If the minimum capacity ‘mc’ is non-positive, this method takes no action and simply returns.
Let’s take an example program based on the above methods such as length(), setLength(), capacity(), and ensureCapacity().
Program code:
public class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Every people love his country"); int length = sb.length(); System.out.println("Length: " + length); int capacity = sb.capacity(); System.out.println("Capacity: " +capacity); sb.ensureCapacity(50); System.out.println("New capacity: " +sb.capacity()); sb.setLength(20); System.out.println("After setLength, New StringBuilder: " +sb); } }
Output: Length: 29 Capacity: 45 New capacity: 92 After setLength, New StringBuilder: Every people love hi
11. toString():
The toString() method returns a string object from the string builder object. The general form to define this method is given below:
public String toString()
12. substring():
This method obtains a substring of string builder object. It has the following two general forms:
String substring(int startIndex) String substring(int startIndex, int endIndex)
The first form returns the substring starting at startIndex and executes to the end of the invoking StringBuffer object.
The second form returns the substring from startIndex to endIndex–1.
Let’s take an example program based on toString() and substring() methods of StringBuilder class.
Program code:
public class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Java Technology"); String str = sb.toString(); System.out.println("String form of StringBuilder: " +str); String s1 = sb.substring(0, 9); System.out.println("Substring: " +s1); } }
Output: String form of StringBuilder: Java Technology Substring: Java Tech
Advantage of using StringBuilder over StringBuffer
There are two main advantages of using StringBuilder class in Java over StringBuffer. They are as:
1. StringBuilder is more efficient if it is accessed by just a single thread, because no synchronization is required in this case.
2. It provides faster performance because thread is not synchronized.
3. Multiple threads can access the same string builder object at a time.
Disadvantage of using StringBuilder Class
Since methods present in StringBuilder class are not synchronized, therefore, StringBuilder is not thread safe.
When to Use String, StringBuffer, or StringBuilder in Java?
1. String is suitable to use when you do not want to modify the content in the string object. String is an immutable class. Once created, its content cannot be changed.
2. StringBuffer can be used when we want to perform any changes in the content and need synchronization. It can be used when you are working in multithreading environment.
3. StringBuilder can be used when you want to create a string within a single thread. It will improve the execution time and performance.
StringBuilder is suitable to use when no thread-safety is needed.
Hope that this tutorial has elaborated almost the important points concerning StringBuilder class in Java and its methods with various example programs. I hope that you will have understood the basic concepts of StringBuilder class.
Thanks for reading!!!
Next ⇒ String vs StringBuffer vs StringBuilder⇐ Prev Next ⇒