QUESTIONS & ANSWERS
JAVA
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:
-
append(String str):- Appends the specified string
strto the end of the currentStringBufferobject. - Returns the modified
StringBufferobject.
- Appends the specified string
-
insert(int offset, String str):- Inserts the specified string
strat the givenoffsetposition in the currentStringBufferobject. - Returns the modified
StringBufferobject.
- Inserts the specified string
-
delete(int start, int end):- Removes the characters from the
startindex (inclusive) to theendindex (exclusive) from the currentStringBufferobject. - Returns the modified
StringBufferobject.
- Removes the characters from the
-
deleteCharAt(int index):- Removes the character at the specified
indexfrom the currentStringBufferobject. - Returns the modified
StringBufferobject.
- Removes the character at the specified
-
replace(int start, int end, String str):- Replaces the characters from the
startindex (inclusive) to theendindex (exclusive) with the specified stringstr. - Returns the modified
StringBufferobject.
- Replaces the characters from the
-
reverse():- Reverses the characters in the current
StringBufferobject. - Returns the modified
StringBufferobject.
- Reverses the characters in the current
-
substring(int start)andsubstring(int start, int end):- These methods are similar to the corresponding methods in the
Stringclass. - The first variant returns the substring starting from the
startindex to the end of theStringBuffer. - The second variant returns the substring from the
startindex (inclusive) to theendindex (exclusive).
- These methods are similar to the corresponding methods in the
-
length():- Returns the length (number of characters) of the
StringBufferobject.
- Returns the length (number of characters) of the
-
capacity():- Returns the current capacity (size) of the
StringBufferobject.
- Returns the current capacity (size) of the
-
setLength(int newLength):
-
- Sets the length of the
StringBufferto the specifiednewLength. - If
newLengthis greater than the current length, theStringBufferwill be padded with null characters ('\0') to reach the desired length. - If
newLengthis smaller than the current length, characters beyond thenewLengthwill be truncated.
- Sets the length of the
charAt(int index)andsetCharAt(int index, char ch):
-
charAt(int index)returns the character at the specifiedindex.setCharAt(int index, char ch)sets the character at the specifiedindexto the givench.
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.