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:
append(String str)
:
str
to the end of the current StringBuilder
object.StringBuilder
object.insert(int offset, String str)
:
str
at the given offset
position in the current StringBuilder
object.StringBuilder
object.delete(int start, int end)
:
start
index (inclusive) to the end
index (exclusive) from the current StringBuilder
object.StringBuilder
object.deleteCharAt(int index)
:
index
from the current StringBuilder
object.StringBuilder
object.replace(int start, int end, String str)
:
start
index (inclusive) to the end
index (exclusive) with the specified string str
.StringBuilder
object.reverse()
:
StringBuilder
object.StringBuilder
object.substring(int start)
and substring(int start, int end)
:
String
class.start
index to the end of the StringBuilder
.start
index (inclusive) to the end
index (exclusive).length()
:
StringBuilder
object.capacity()
:
StringBuilder
object.setLength(int newLength)
:
StringBuilder
to the specified newLength
.newLength
is greater than the current length, the StringBuilder
will be padded with null characters ('\0') to reach the desired length.newLength
is smaller than the current length, characters beyond the newLength
will be truncated.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.