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:

  1. Instantiate a StringBuilder object:
  2. StringBuilder sb = new StringBuilder(); // Instantiate a new empty StringBuilder object
    StringBuilder sb = new StringBuilder(“Hello”); // Instantiate a new StringBuilder object with initial content
  3. Concatenation of strings:
  4. 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
  5. String deletion:
  6. 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
  7. String replacement:
  8. sb.replace(0, 5, “Hi”); // Replace a specified portion of the string
    sb.setCharAt(0, ‘H’); // Replace a specified character at a position
  9. Reverse a string.
  10. Reverse the string in the StringBuilder object.
  11. Obtain the length of the string:
  12. Obtain the length of the string in the StringBuilder object.
  13. Convert to a String object:
  14. 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.

bannerAds