Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes


Modifying StringBuffers

class ReverseString {
    public static String reverseIt(String source) {
	int i, len = source.length();
	StringBuffer dest = new StringBuffer(len);

	for (i = (len - 1); i >= 0; i--) {
	    dest.append(source.charAt(i));
	}
	return dest.toString();
    }
}
The reverseIt method uses StringBuffer's append() method to add a character to the end of the destination string: dest. If the appended character causes the size of the StringBuffer to grow beyond its current capacity, the StringBuffer allocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by minimizing the number of times memory must be allocated for a StringBuffer by initializing its capacity to a reasonable first guess. For example, the reverseIt method constructs the StringBuffer with an initial capacity equal to the length of the source string ensuring only one memory allocation for dest.

Using append() to add a character to the end of a StringBuffer is only one of StringBuffer's methods that allow you to append data to the end of a StringBuffer. There are several append() methods that append data of various types, such as float, int, boolean, and even Object, to the end of the StringBuffer. The data is converted to a string before the append takes place.

Insertion

At times, you may want to insert data into the middle of a StringBuffer. You do this with one of StringBufffer's insert() methods. This example illustrates how you would insert a string into a StringBuffer.
StringBuffer sb = new StringBuffer("Drink Java!");
sb.insert(6, "Hot ");
System.out.println(sb.toString());
This code snippet prints
Drink Hot Java!
With StringBuffer's many insert(), you specify the index before which you want the data inserted. In the example, "Hot " needed to be inserted before the 'J' in "Java". Indices begin at 0, so the index for 'J' is 6. To insert data at the beginning of a StringBuffer use an index of 0. To add data at the end of a StringBuffer use an index equal to the current length of the StringBuffer or use append().

Set Character At

Another useful StringBuffer modifier is setCharAt() which sets the character at a specific location in the StringBuffer. setCharAt() is useful when you want to reuse a StringBuffer.


Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes