Java Reference
In-Depth Information
Method
Description
insert(int index,
Inserts a substring into the StringBuffer object starting at
position index . The substring is the String representation of
length characters from the str[] array, starting at position
offset .
char[] str,
int offset,
int length)
If the value of index is outside the range of the string in the StringBuffer object, or the offset or
length values result in illegal indexes for the array, str , then an exception of type
StringIndexOutOfBoundsException will be thrown.
Extracting Characters from a StringBuffer Object
The StringBuffer includes the charAt() and getChars() methods, both of which work in the same
way as the methods of the same name in the class String which we've already seen. The charAt()
method extracts the character at a given index position, and the getChars() method extracts a range of
characters and stores them in an array of type char starting at a specified index position. You should note
that there is no equivalent to the getBytes() method for StringBuffer objects.
Other StringBuffer Operations
You can change a single character in a StringBuffer object by using the setCharAt() method.
The first argument indicates the index position of the character to be changed, and the second argument
specifies the replacement character. For example, the statement:
buf.setCharAt(3, 'Z');
will set the fourth character in the string to ' Z '.
You can completely reverse the sequence of characters in a StringBuffer object with the
reverse() method. For example, if you define the object with the declaration:
StringBuffer palindrome = new StringBuffer("so many dynamos");
you can then transform it with the statement:
palindrome.reverse();
which will result in palindrome containing the useful phrase " somanyd ynam os ".
Creating a String Object from a StringBuffer Object
You can produce a String object from a StringBuffer object by using the toString() method of
the StringBuffer class. This method creates a new String object and initializes it with the string
contained in the StringBuffer object. For example, to produce a String object containing the
proverb that we created in the previous section, you could write:
Search WWH ::




Custom Search