StringBuilder in Java with Examples, Methods and Constructors

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

StringBuilder class

Overview

The StringBuilder in Java is used for storing the mutable (changeable) sequence which means we can update the elements of the StringBuilder class without creating a new StringBuilder sequence in memory.

Introduction

StringBuilder in Java is an alternative to String class in Java. String class creates immutable string objects which means once a String object is declared, it cannot be modified. However, the StringBuilder class represents a mutable sequence of characters. StringBuilder class is very similar to StringBuffer class. Both these classes are alternative to String class and create mutable character sequences.

However, StringBuilder class operations are faster than StringBuffer because StringBuilder class is not thread-safe. The StringBuilder class provides no guarantee of synchronization, however StringBuffer class operations are synchronized. However, in most cases, operations on a string are performed on the same thread, hence StringBuilder class can be used. StringBuilder class is preferred over StringBuffer class due to its faster operations.

What is StringBuilder in java?

Let's declare an object of the String class:

When we manipulate this string object in any way, instead of performing modifications in the same string object pointed to by str, a new String object with the new value is created in the heap memory. This not only causes memory wastage but also delays string manipulations.

To solve these problems, we use StringBuilder class to represent a sequence of characters. `Stringbuilder in Java holds mutable strings which means string manipulations are performed on the same sequence instead of creating new string objects every time the string is manipulated.

Syntax of Stringbuilder in Java

StringBuilder class extends the Object class and implements the Serializable and CharSequence interfaces.

syntax of stringbuilder class

Internal Working of StringBuilder in Java

StringBuilder class maintains a buffer array to hold the sequence of characters. When the sequence of characters is altered(manipulated), the buffer array is changed accordingly to reflect the manipulation. For example, if a new character is added to the existing string, the buffer array is appended with the new character.

Now think about what will happen when the buffer gets full? When the buffer array gets full, a new buffer array, double the size, is allocated to replace the existing array.

Let's discuss the contractors of the StringBuilder class.

Constructors of StringBuilder in Java

StringBuilder class provides different types of constructors that help for converting the ordinary Sequence, characters to StringBuilder format and helps to configure some properties of StringBuilder size as size, etc. Let's discuss different Constructors one by one.

ConstructorDescription
StringBuilder()It generates an empty String Builder with a 16-character initial capacity.
StringBuilder(int capacity)It generates a new, empty String Builder with the provided length for capacity.
StringBuilder(char sequence)This constructor is used to create a StringBuilder from a character sequence.
StringBuilder(String)The provided string is used to generate a String Builder.

1. StringBuilder()

This constructor is used for creating a StringBuilder object with no characters in it and initial capacity of 16 characters.

Syntax:

2. StringBuilder(int capacity)

This constructor is used for creating a StringBuilder object with no characters in it and an initial capacity specified by the capacity argument.

Syntax:

In this example, we have created a StringBuilder object with initial capacity of 10 characters.

3. StringBuilder(CharSequence seq)

This constructor is used for creating a StringBuilder object with initial characters specified by the CharSequence argument seq. The initial capacity of this object is 16 + the length of CharSequence argument seq.

Syntax:

4. StringBuilder(String str):

This constructor is used for creating a StringBuilder object with initial content the same as str characters and initial capacity = 16 + length of str.

Syntax:

Example

Let's understand these constructors with the help of an example.

Output:

Methods of StringBuilder in Java

StringBuilder class provides various types of inbuilt methods that help in performing different kinds of operations on StringBuilder. Let's discuss each method one by one.

MethodDescription
public StringBuilder append(String s)It is utilized to append the specified string to the provided string. This function is overloaded.
public StringBuilder insert(int offset, String s)This string is used to insert the provided string at the designated place.
public StringBuilder replace(int startIndex, int endIndex, String str)The string from the startIndex and endIndex values are replaced using this method.
public StringBuilder delete(int startIndex, int endIndex)It is used to delete the string from startIndex and endIndex that are provided.
public StringBuilder reverse()It is used to reverse the string.
public int capacity()It is used to return the current capacity.
public void ensureCapacity(int minimumCapacity)It's used to make sure that the capacity is at least equal to the minimum specified.
public char charAt(int index)It is utilised to retrieve the character at the requested location.
public int length()The length of the string, or the total number of characters, is returned using this method.
public String substring(int beginIndex)The substring starting at the supplied beginIndex is returned using it.
public String substring(int beginIndex, int endIndex)It is used to retrieve the substring starting at the beginIndex and endIndex values supplied.

1. append() Method

This method is used for appending the new sequence in the exisiting sequence of the StringBuilder class.

Syntax:

StringBuilder.append(): The append() method of the StringBuilder class is used for appending the element of a particular datatype at the end of the current sequence of the StringBuilder also there is no error occur if we append the values in the empty StringBuilder sequence.

Parameter: This method takes one parameter that is any datatype value that needs to be appended in the StringBuilder sequence.

ReturnType: This method returns the reference of StringBuilder object

In the above program, we are appending a different kinds of datatype values to the sequence of StringBuilder. In the above case, we are appending the int and String datatypes values to the StringBuilder sequence.

Output:

  • appendCodePoint() method is used for appending the String representation of the unicode characters to the sequence of the StringBuilder. For example the unicode value of character 'A' is 67. This unicode value is converted to the String "A" and then append to the sequence of the StringBuilder class.

Syntax:

StringBuilder appendCodePoint(int value): This method takes the Unicode value and adds the String representation of the Unicode at the end of the sequence of StringBuilder.

Parameter: This method takes one value, the Unicode value as a parameter.

Return type: This method returns the object reference of the StringBuilder class.

Let' understand this method using an example.

Output:

In the above snippet, we are adding the Unicode value of 'a' to the StringBuilder sequence and the resultant sequence is Scalera.

2. capacity() method:

This method is used for finding the intial capacity of the StringBuilder object. The default capacity of StringBuilder class is 16 bytes.

Syntax:

int capacity(): This method returns the capacity of the StringBuilder object. The default capacity of the StringBuilder is 16 bytes. When the capacity of StringBuilder gets full the new capacity of StringBuilder will be (previouscapacity+1)X2.

Return type: This method returns the current capacity in int format.

Let's understand this method using an example.

Output:

In the above snippet, the capacity of the StringBuilder sequence increases when the capacity gets full. Default capacity is 16 and the new capacity is (16+1)*2 i.e 34.

3. charAt() method:

  • char charAt(index): This method is used for getting character value present at the index of the StringBuilder sequence.

Parameter: This method takes one parameter the index of the character. The range of index must be in the range [0, SizeofStringBuilder-1]. if the value of the index outside the range this cause an indexoutofException and program will be stopped.

Return type: This method returns the character present at the index value in the StringBuilder sequence.

Let's understand this method using an example.

Output:

The above snippet is printing the character that is present at index 0 and the second printing line is causing an error due to the invalid range of index value.

  • deleteCharAt() method: This method is used for deleting the particular character at the given index from the StringBuilder sequence.

Syntax:

  • StringBuilder.deleteCharAt(index): This method is used for delete a particular character present at the index in the StringBuilder sequence.

Parameter: This method takes one parameter i.e the index of the character.

Return type: This return type of this method is StringBuilder reference.

Let's understand this method using an example.

Output:

The above snippet is used for deleting the character at index 2 of StringBuilder Scaler.

  • setCharAt() method: This method is used for inserting the character at the particular index of the StringBuilder sequence.

Syntax:

  • void setCharAt(index, char c): This method is used for inserting the character at the particular index in the StringBuilder sequence. The range of index should be in [0-lengthofsequence].

Parameter: This method takes two parameters one is the index value and the second parameter is the character that to is inserted at the index position in the StringBuilder sequence. if the value of the index outside the range this cause an indexoutofException and program will be stopped.

Return type: The return type of this method is void.

Example:

Output:

The first printing line will print the updated sequence of the StringBuilder, but the second printing line will cause an error due the invalid range of the index in the parameter of the method.

4. reverse() method:

This method is used for reversing the StringBuilder sequence.

Syntax:

StringBuilder.reverse(): This method is used for reverse the StringBuilder sequence.

Parameter: This method doesn't take any parameters.

Return type: This method return StringBuilder reference.

Example:

Output:

The above snippet reverse the StringBuilder sequence i.e Scaler to relcaS.

5. length() method:

This method is used for finding the length of the StringBuilder sequence. Length is the number of elements of the StringBuilder sequence.

Syntax:

StringBuilder.length(): This method is used for calculating the length of the StringBuilder sequence.

Parameter: This method doesn't take any parameters.

Return type: This method returns the length of the StringBuilder sequence.

Example:

Output:

The above snippet is printing the length of the StringBuilder sequence i.e 6 is the length of the sequence in the above snippet.

6. indexof() method:

This method is used for finding the first index of the given String in the sequence of the StringBuilder.If the String is not present in the sequence of the StringBuilder this method will return -1.

Syntax:

  • int indexof(String): This method returns the first index of the given String in the sequence if it is present, Otherwise this method returns -1 that indicates String is not present in the StringBuilder sequence.

Parameter: This method takes one parameter i.e String.

Return type: This method returns the first index value of String if present, otherwise returns -1.

Example:

Output:

In the above snippet, the "S" String occurs at the first index of the StringBuilder sequence that's why we get 0 in the first printing statement, but in the second printing line, we get -1 because "z" String is not present in the sequence of StringBuilder.

7. lastIndexof() method:

This method is used for finding the last index of the particular sequence in the StringBuilder sequence. If the sequence is not present in the StringBuilder sequence. This method returns -1, otherwise will return the starting index value of the sequence.

Syntax:

int lastIndexof(String): This method returns the last index of the given String in the sequence of the StringBuilder.

Parameter: This method takes one parameter i.e String.

Return type: This method returns the last index of the String, if it is present in the Sequence of StringBuilder, Otherwise returns -1.

Example:

Output:

In the above snippet, the first printing line will return the last index of String i.e Scaler that is present at index 6, So 6 is returns but in the second printing line "z" String is not present in the sequence of the StringBuilder that's why -1 is prints.

8. isEmpty() method:

This method is used to check whether the StringBuilder object contains any sequence or not.

Syntax:

StringBuilder.isEmpty(): If the StringBuilder sequence is empty this method will return true otherwise returns false. When the StringBuilder sequence is not empty.

Parameter: This method doesn't take any parameters.

Return type: The return type of this method is boolean i.e either true or false.

Let's understand this method using an example.

Output:

The true value is returned because at the starting the StringBuilder is empty but appending the text to the StringBuilder contains some sequence that why false is returned.

9. substring() method:

This method is used for getting the substring from the StringBuilder sequence.

Syntax:

StringBuilder.substring(start index,endingindex+1): This method takes two parameters to start index of the sequence and the ending index of the sequence. The starting index must be greater than 0 and smaller and equal to the ending index.

Parameter: This method takes two parameters i.e Starting index and the ending index of the sequence.

Return type: The return type of this method is String.

Let's understand this method using an example.

Output:

The string "sh" is returned because we want substring starting from index 4 and "yus" is returned because the index of y is 2 and the ending index is 4 that's why we get substring "yus".

10. delete() method:

This method is used for deleting the particular sequence from the StringBuilder.

  • Syntax:

StringBuilder.delete(startindex,endingindex+1) method takes two arguments startingindex and the endingindex of the sequence that we want to delete from the StringBuilder sequence.

Parameter: This method takes two parameters the starting index must be greater than equal to 0 and smaller than equal to the ending index.

Return type: This method returns the StringBuilder reference.

Output:

The seqeunce Aayu is returned because we have deleted the sequence starting from index 4 i.e sh and in the next deletion we delete the sequence starting from index 2 and ending index 5(empty sequence) that's why Aa is returned.

These are some methods of the StringBuilder class.

Calling StringBuilder Methods

We can call StringBuilder class methods using the object of the StringBuilder class.Because StringBuilder class is not a primitive class that's means we have to create a StringBuilder object for accessing its methods.

Let's understand how to call StringBuilder methods using an example.

Output:

In the above snippet, we are appending the "Scaler" text in the StringBuilder sequence.

StringBuilder Length and Capacity.

StringBuilder.length() and StringBuilder.capacity() are the two methods of the StringBuilder class are somewhat make sense similar but they are totally different.

StringBuilder.Capacity() This method indicates the maximum number of elements the StringBuilder object can hold. When the StringBuilder capacity gets full.

Internally StringBuilder updates the capacity by (previouscapcity+1)*2. By default 16 bytes is the capacity of the StringBuilder when StringBuilder contains no elements.

java stringbuilder capacity

In the above image, the capacity of the StringBuilder is 16 bytes but the current sequence length is 9 bytes.

StringBuilder.length(): The method tells us the length of the current StringBuilder sequence that means the number of characters of the StringBuilder sequence. The length of the StringBuilder is always smaller and equal to the capacity of the StringBuilder capacity. In the above picture, the number of characters of StringBuilder sequence is 9 that's why the length is 8.

Performing StringBuilder Operations

  • Iterating StringBuilder characters: Using the for loop is one of the best ways for iterating the characters of the StringBuilder.

Let's understand this using an example.

Example:

Output:

In the above snippet we are iterating on the characters of the StringBuilder sequence with the help of the String.charAt(index) method and for a loop.

  • Adding text to a StringBuilder object: The append() method of the StringBuilder class is used for appending the text in the current sequence of StringBuilder.

Let's understand how to add text to a StringBuilder object using an example.

Output:

  • Modifying the text in the StringBuilder object: We can modify the existing StringBuilder sequence in two ways either deleting the some elements of the sequence or inserting the text in the StringBuilder sequence. For inserting the text at the particular index, we will use StringBuilder.insert(index,text) method of the StringBuilder class.

Example:

Output:

The above snippet is inserting the text at the 2nd index of the existing sequence of the StringBuilder.

  • Deleting the text from StringBuilder object: We can delete the text from the StringBuilder sequence using StringBuilder.delete(startindex,endindex+1) method. Let's understand how to delete the text from the StringBuilder sequence using an example.

Output:

In the above snippet, we delete the Hello from the StringBuilder sequence that is present at the starting index 6 and ends at the 10th index.

Searching The Text in a StringBuilder Object

If we want to search particular text in the StringBuilder object. We can use StringBuilder.indexOf(text) method. This method returns the first index of the text if it is present in the StringBuilder sequence, otherwise returns -1.

Let's understand how to search the text in the StringBuilder object using an example.

Output:

The world is present in the StringBuilder sequence at the starting index 11 but the text "ScalerZ" is not present in the StringBuilder sequence that's why -1 will return.

Converting The StringBuilder Object to a String

Suppose you want to change the StringBuilder object to String because next operations need String an input instead of StringBuilder in a particular program. What should you do? StringBuilder class provides a method StringBuilder.toString() that converts the StringBuilder object to the String object.

Let's understand StringBuilder.toString() method using an example.

FAQ's:

1. What is the use of String builder?

StringBuilder class is used for storing the mutable elements that save lots of memory because no extra memory is used after updation on the StringBuilder sequence.

2. Why do we use StringBuilder in Java?

Because it is not thread-safe multiple threads can access the StringBuilder object that increases the performance of StringBuilder because no thread has to wait for their turn for a particular operation.

3. Is StringBuilder in Java efficient?:

Yes, StringBuilder is efficient because due to the mutable and non-thread-safe property of the StringBuilder.

4. Which is better: StringBuilder or String?

StringBuilder is better because it is 6000 times faster than the String class.

Conclusion

  • StringBuilder class is used for storing mutable elements.
  • StringBuilder is non-synchronous multiple threads can access the StringBuilder object at the same time.
  • StringBuilder is the fastest among all the other String classes such as String and StringBuffer.
  • The default capacity of the StringBuilder is 16 bytes.

See Also