JAVA Syllabus
QUESTIONS & ANSWERS

Explain all important methods of StringBuilder class?

StringBuilder is similar to StringBuffer in functionality but is not thread-safe, making it more efficient in single-threaded environments. It provides several methods to manipulate and modify strings efficiently. Here are some of the important methods in the StringBuilder class:

  1. append(String str):

    • Appends the specified string str to the end of the current StringBuilder object.
    • Returns the modified StringBuilder object.
  2. insert(int offset, String str):

    • Inserts the specified string str at the given offset position in the current StringBuilder object.
    • Returns the modified StringBuilder object.
  3. delete(int start, int end):

    • Removes the characters from the start index (inclusive) to the end index (exclusive) from the current StringBuilder object.
    • Returns the modified StringBuilder object.
  4. deleteCharAt(int index):

    • Removes the character at the specified index from the current StringBuilder object.
    • Returns the modified StringBuilder object.
  5. replace(int start, int end, String str):

    • Replaces the characters from the start index (inclusive) to the end index (exclusive) with the specified string str.
    • Returns the modified StringBuilder object.
  6. reverse():

    • Reverses the characters in the current StringBuilder object.
    • Returns the modified StringBuilder object.
  7. substring(int start) and substring(int start, int end):

    • These methods are similar to the corresponding methods in the String class.
    • The first variant returns the substring starting from the start index to the end of the StringBuilder.
    • The second variant returns the substring from the start index (inclusive) to the end index (exclusive).
  8. length():

    • Returns the length (number of characters) of the StringBuilder object.
  9. capacity():

    • Returns the current capacity (size) of the StringBuilder object.
  10. setLength(int newLength):

    • Sets the length of the StringBuilder to the specified newLength.
    • If newLength is greater than the current length, the StringBuilder will be padded with null characters ('\0') to reach the desired length.
    • If newLength is smaller than the current length, characters beyond the newLength will be truncated.
  1. charAt(int index) and setCharAt(int index, char ch):
    • charAt(int index) returns the character at the specified index.
    • setCharAt(int index, char ch) sets the character at the specified index to the given ch.

These methods provide a wide range of string manipulation functionalities, making StringBuilder a powerful tool for building and modifying strings efficiently in Java. Remember that StringBuilder is mutable, so you can modify its contents and perform various string operations without creating multiple objects.

31/07/2023, 12:36 pm Read : 117 times