What is the usage of the StringBuilder class in Java?
The StringBuilder class is a mutable string class that offers a range of methods for manipulating strings. Unlike the String class, objects of the StringBuilder class can be modified without creating new objects.
Below are common uses of the StringBuilder class:
- Instantiate a StringBuilder object:
- StringBuilder sb = new StringBuilder(); // Instantiate a new empty StringBuilder object
StringBuilder sb = new StringBuilder(“Hello”); // Instantiate a new StringBuilder object with initial content - Concatenation of strings:
- sb.append(” World”); // Add the string ” World” at the end of the StringBuilder object
sb.insert(0, “Hello “); // Insert the string “Hello ” at the specified position - String deletion:
- sb.delete(5, 10); // Delete characters at specified positions
sb.deleteCharAt(5); // Delete character at specified position
sb.delete(0, sb.length()); // Clear the StringBuilder object - String replacement:
- sb.replace(0, 5, “Hi”); // Replace a specified portion of the string
sb.setCharAt(0, ‘H’); // Replace a specified character at a position - Reverse a string.
- Reverse the string in the StringBuilder object.
- Obtain the length of the string:
- Obtain the length of the string in the StringBuilder object.
- Convert to a String object:
- Convert the StringBuilder object to a String object and assign it to the variable “str”.
It is important to note that since the StringBuilder class is not thread-safe, when used in a multi-threaded environment, the StringBuffer class should be used instead.