Working with StringBuilder Class
StringBuilder objects are similar to String objects, except that they are mutable. Internally, the system treats these objects as a variable-length array containing a sequence of characters. The length and content of the sequence of characters can be changed through methods available in the StringBuilder class. However, developers prefer to use String class unless StringBuilder offers an advantage of simpler code in some cases. For example, for concatenating a large number of strings, using a StringBuilder object is more efficient.
The StringBuilder class also provide a length() method that returns the length of the character sequence in the class.
However, unlike strings a StringBuilder object also has a property capacity that specifies the number of character spaces that have been allocated. The capacity to hold data in the instance of the StringBuilder class will automatically expand according to the user requirement to accommodate the new strings when added to the string builder.
Thus, the StringBuilder class is used for manipulating the String object. Objects of StringBuilder class are mutable and flexible. StringBuilder object allows insertion of characters and strings as well as appending characters and string at the end.
The constructors of the StringBuilder class are as follows:
- StringBuilder(): Default constructor that provides space for 16 characters.
- StringBuilder(int capacity): Constructs an object without any characters in it. However, it reserves space for the number of characters specified in the argument, capacity.
- StringBuilder(String str): Constructs an object that is initialized with the contents of the specified string, str.
Methods of StringBuilder Class
The StringBuilder class provides several methods for appending, inserting, deleting, and reversing string as follows:
- append() : The append() method is used to append values at the end of the StringBuilder object. This method accepts different types of argument, including char, int, float, double, boolean, and so on, but the most common argument is String.
- insert(): The insert() method is used to insert one string into another. Similar to the append() method, it calls the String.valueOf() method to obtain the string representation of the value. The new string is inserted into the invoking StringBuildr object.
- Delete(): The delete() method deletes the specified number of characters from the invoking StringBuilder object.
- reverse(): The reverse() method used to reverse the characters within a StringBuilder object.