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
str
to the end of the currentStringBuffer
object. - Returns the modified
StringBuffer
object.
- Appends the specified string
-
insert(int offset, String str)
:- Inserts the specified string
str
at the givenoffset
position in the currentStringBuffer
object. - Returns the modified
StringBuffer
object.
- Inserts the specified string
-
delete(int start, int end)
:- Removes the characters from the
start
index (inclusive) to theend
index (exclusive) from the currentStringBuffer
object. - Returns the modified
StringBuffer
object.
- Removes the characters from the
-
deleteCharAt(int index)
:- Removes the character at the specified
index
from the currentStringBuffer
object. - Returns the modified
StringBuffer
object.
- Removes the character at the specified
-
replace(int start, int end, String str)
:- Replaces the characters from the
start
index (inclusive) to theend
index (exclusive) with the specified stringstr
. - Returns the modified
StringBuffer
object.
- Replaces the characters from the
-
reverse()
:- Reverses the characters in the current
StringBuffer
object. - Returns the modified
StringBuffer
object.
- Reverses the characters in the current
-
substring(int start)
andsubstring(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 theStringBuffer
. - The second variant returns the substring from the
start
index (inclusive) to theend
index (exclusive).
- These methods are similar to the corresponding methods in the
-
length()
:- Returns the length (number of characters) of the
StringBuffer
object.
- Returns the length (number of characters) of the
-
capacity()
:- Returns the current capacity (size) of the
StringBuffer
object.
- Returns the current capacity (size) of the
-
setLength(int newLength)
:
-
- Sets the length of the
StringBuffer
to the specifiednewLength
. - If
newLength
is greater than the current length, theStringBuffer
will be padded with null characters ('\0') to reach the desired length. - If
newLength
is smaller than the current length, characters beyond thenewLength
will 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 specifiedindex
to 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.