Class relations: + java.lang.Object + - java.lang.StringBuffer
Implemented interfaces: Serializable, Appendable, CharSequence
Thread-safe: True
StringBuffer is a class that represent a mutable sequence of characters. Unlike the String
type which is immutable. StringBuffer objects can be modified after they are created, this makes it useful and more efficient over String
when performing a lot of modifications on a string such as appending, inserting, and deleting characters.
StringBuffer provides much of the functionality of the string class, it has a growable capacity, when inserting and appending characters exceed the current capacity, it will automatically grow to make room to accommodate such operations. StringBuffer often preallocates more capacity than currently needed to minimise the number of reallocations and improve performance, the default capacity of StringBuffer upon initialisation for an empty string is 16.
StringBuffer is thread-safe, all its methods are synchronised and can be safely used by multiple threads.
hello
StringBuffer constructors
StringBuffer has three constructors allowing initialising a StringBuffer
object depending on different needs.
StringBuffer()
- The default constructor creates an empty StringBuffer with an initial capacity of 16.
StringBuffer(String str)
- Creates a StringBuffer with the specified string.
StringBuffer(int capacity)
- Creates an empty StringBuffer with the specified capacity.
StringBuffer methods
Method | Description | Ref |
---|---|---|
int capacity() | It returns the current capacity | |
int length() | It returns the length (character count) | |
StringBuffer append(String s) | It appends the specific string to the calling string. This is an overloaded method to support other types | |
StringBuffer insert(int offset, String s) | It inserts the specific string to a specific position in the calling string. This is an overloaded method to support other types | |
StringBuffer replace(int startIndex, int endIndex, String str) | It replaces the string from specified startIndex and endIndex with the specific string | |
StringBuffer delete(int startIndex, int endIndex) | It deletes the string from specified startIndex and endIndex | |
StringBuffer deleteCharAt(int index) | It removes the char at the specified position | |
void setCharAt(int index, char ch) | It sets the character at the specified index to ch | |
StringBuffer reverse() | It reverses the string | |
void ensureCapacity(int minimumCapacity) | It is used to ensure the capacity at least equal to the given minimum, useful when the approximate size of the buffer in known in advance, to avoid frequency of reallocations | |
char charAt(int index) | It returns char value for the particular index | |
String substring(int beginIndex) | It returns a substring for given begin index | String Class |
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaStringStringBuffer
Reference: