A Quick Guide to String Builder in Java
StringBuilder class
Java provides us StringBuilder class that represents a mutable collection of characters. This class was introduced as an alternative to the String class as the String class object cannot be modified. StringBuilder class is defined under the java.lang package.
The class hierarchy is given below:
The StringBuilder class is similar to the StringBuffer class as both can be used to make a mutable string but differ in terms of synchronization. The StringBuffer class promises synchronization whereas the StringBuilder class doesn’t guarantee synchronization.
The syntax of the StringBuilder class is the following:
public final class StringBuilder |
Constructors provided under StringBuilder class
StringBuilder class provides the following constructors in it:
- StringBuilder(): This is similar to a default constructor having no parameters. This constructor creates a string builder having no characters in it. The created string builder object has an initial capacity of 16 characters.
- StringBuilder(int capacity): It is parameterized constructor that creates a string builder having no characters in it. In this case, the initial capacity is provided by the capacity argument.
- StringBuilder(CharSequence seq): This constructor creates a string builder object that contains the same set of characters as provided as an argument while calling the constructor(CharSequence).
- StringBuilder(String str): This constructor creates a string builder that is initialized with the characters of the specified string.
Let us consider an example below to understand the working of the StringBuilder class:
Source Code:
class HelloWorld { |
Output:
String builder class also contains inbuilt methods in it. Some of these methods are given below:
- StringBuilder append(str): This method is used to append the string representation of the str type argument at the end of the sequence.
- StringBuilder appendCodePoint(int codePoint): Using this method we can append the string representation of the codePoint argument to this sequence.
- int capacity(): This method can be used to get the capacity of an object.
- char charAt(int index): This method is used to get the character stored at the specified index of the sequence.
- int indexOf(): This method is used to get the index within this string of the very first occurrence of the substring passed to this method.
- StringBuilder reverse(): This method causes the current sequence of characters to be replaced by the reverse of the original sequence.
Now we will see a program demonstrating the working of these methods:
Source Code:
class HelloWorld { |
Output:
Conclusion
In this article, we started with introducing StringBuilder class in Java. We also learned about different types of constructors defined in this class. Later, we discussed different member functions defined under this class.