OOPS/JAVA : StringBuffer
by hkesavaraju on Feb.27, 2010, under Java
StringBuffer
It is a peer class of String that provides string functionality. It is a growable and changeable character sequences.
I. StringBuffer constructors: (i) StringBuffer(): It allocates room for 16 characters without reallocation and is the default constructor.
(ii) StringBuffer(int size): It takes string buffer size as an argument size.
-
StringBuffer(String str): It sets its initial contents as argument string str and allocates 16 more characters without reallocation.
It has length() which returns the number of characters in given string buffer where as capacity() returns total allocated capacity for a given string.
II. Modification Methods: These methods when performed in a given string buffer object that reflects in original string buffer object.
-
append(): It concatenates any other type of data to the end of invoking string. It’s versions are:
-
Stringbuffer append(String str)
-
Stringbuffer append(int num)
-
Stringbuffer append(Object obj)
-
-
insert(): It inserts one string into another. It’s forms as follows:
-
StringBuffer insert(int index, char ch): It inserts character ch at specified index .
-
StringBuffer insert(int index, String str): It inserts string str at specified index .
-
StringBuffer insert(int index, Object obj): It inserts object obj at specified index .
-
-
reverse(): It returns reverse of the characters in given StringBuffer object.
It’s form is StringBuffer reverse()
-
delete() and deletecharAt(): Its forms are
a)StringBuffer delete(int StartIndex, int endIndex) : It removes the characters in an invoking string from startIndex to endIndex-1.
b) StringBuffer deleteChatAt(int loc) : It deletes the character specified at loc index in an invoking string.
(v) replace(): It’s from is StringBuffer replace(int StartIndex, int endIndex, String str) replaces in a given string from startIndex to endIndex-1 with str.
(vi) substring(): IT returns portion of a StringBuffer object. It’s forms are
-
String substring(int startIndex): It returns a portion of string from startIndex to last index.
-
String substring(int startIndex, int endIndex): It returns a portion of string from startIndex to endIndex.-1.