Java Reference
In-Depth Information
This will append the string " exactly " to buf , so after executing this statement buf will contain " The
number is 99912.34 exactly ".
You may be somewhat bemused by the plethora of append() method options, so let's collect all the
possibilities together. You can append any of the following types to a StringBuffer object:
boolean
char
String
Object
int
long
float
double
byte
short
You can also append an array of type char[] , and a subset of the elements of an array of type
char[] . In each case the String equivalent of the argument is appended to the string in the
StringBuffer object.
We haven't discussed type Object - it is here for the sake of completeness. You will learn about this
type of object in Chapter 6.
Inserting Strings
To insert a string into a StringBuffer object, you use the insert() method of the object. The first
argument specifies the index of the position in the object where the first character is to be inserted. For
example, if buf contains the string " Many hands make light work ", the statement:
buf.insert(4, " old");
will insert the string " old " starting at index position 4, so buf will contain the string " Many old hands
make light work " after executing this statement.
There are many versions of the insert() method that will accept a second argument of any of the
same range of types that apply to the append() method, so you can use any of the following with the
insert() method:
boolean
char
String
Object
int
long
float
double
byte
short
In each case the string equivalent of the second argument is inserted starting at the index position
specified by the first argument. You can also insert an array of type char[] , and if you need to insert a
subset of an array of type char[] into a StringBuffer object, you can call the version of insert()
that accepts four arguments:
Search WWH ::




Custom Search