The String and StringBuffer Classes |
ThereverseIt
method usesStringBuffer
'sappend
method to add a character to the end of the destination string:dest
.If the appended character causes the size of theclass 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(); } }StringBuffer
to grow beyond its current capacity, theStringBuffer
allocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by initializing aStringBuffer
's capacity to a reasonable first guess, thereby minimizing the number of times memory must be allocated for it. For example, thereverseIt
method constructs theStringBuffer
with an initial capacity equal to the length of the source string, ensuring only one memory allocation fordest
.The version of the
append
method used inreverseIt
is only one of theStringBuffer
methods that appends data to the end of aStringBuffer
. There are severalappend
methods that append data of various types, such asfloat
,int
,boolean
, and evenObject
, to the end of theStringBuffer
. The data is converted to a string before the append operation takes place.Inserting Characters
At times, you may want to insert data into the middle of aStringBuffer
. You do this with one of StringBufffer'sinsert
methods. This example illustrates how you would insert a string into aStringBuffer
:This code snippet prints:StringBuffer sb = new StringBuffer("Drink Java!"); sb.insert(6, "Hot "); System.out.println(sb.toString());WithDrink Hot Java!StringBuffer
's manyinsert
methods, 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 aStringBuffer
, use an index of 0. To add data at the end of aStringBuffer
, use an index equal to the current length of theStringBuffer
or useappend
.Setting Characters
Another usefulStringBuffer
modifier issetCharAt
, which replaces the character at a specific location in theStringBuffer
with the character specified in the argument list..setCharAt
is useful when you want to reuse aStringBuffer
.
The String and StringBuffer Classes |