JAVA Syllabus
QUESTIONS & ANSWERS

Explain all important methods of StringBuffer class?

StringBuffer is a class in Java that represents a mutable sequence of characters. It provides several methods to manipulate and modify strings efficiently. Here are some of the important methods in the StringBuffer class:

  1. append(String str):

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

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

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

    • Removes the character at the specified index from the current StringBuffer object.
    • Returns the modified StringBuffer 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 StringBuffer object.
  6. reverse():

    • Reverses the characters in the current StringBuffer object.
    • Returns the modified StringBuffer 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 StringBuffer.
    • 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 StringBuffer object.
  9. capacity():

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

    • Sets the length of the StringBuffer to the specified newLength.
    • If newLength is greater than the current length, the StringBuffer 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 are some of the most commonly used methods in the StringBuffer class. Keep in mind that StringBuffer is a mutable class, which means you can modify its contents and perform various string manipulation operations efficiently.

31/07/2023, 12:21 pm Read : 171 times