Object String CharSequence char[]
boolean char int long
float double
There are also append and insert methods that take part of a CharSequence or char array as an
argument. Here is some code that uses various append invocations to create a StringBuilder that
describes the square root of an integer:
String sqrtInt(int i) {
StringBuilder buf = new StringBuilder();
buf.append("sqrt(").append(i).append(')');
buf.append(" = ").append(Math.sqrt(i));
return buf.toString();
}
The append and insert methods return the StringBuilder object itself, enabling you to append to the
result of a previous append.
A few append methods together form the java.lang.Appendable interface. These methods are
public Appendable append(char c)
public Appendable append(CharSequence seq)
public Appendable append(CharSequence seq, int start, int end)
The Appendable interface is used to mark classes that can receive formatted output from a
java.util.Formatter objectsee "Formatter" on page 624.
The insert methods take two parameters. The first is the index at which to insert characters into the
StringBuilder. The second is the value to insert, after conversion to a String if necessary. Here is a
method to put the current date at the beginning of a buffer:
public static StringBuilder addDate(StringBuilder buf) {
String now = new java.util.Date().toString();
buf.insert(0, now).insert(now.length(), ": ");
return buf;
}
The addDate method first creates a string with the current time using java.util.Date, whose default
constructor creates an object that represents the time it was created. Then addDate inserts the string that
represents the current date, followed by a simple separator string. Finally, it returns the buffer it was passed so
that invoking code can use the same kind of method concatenation that proved useful in StringBuilder's
own methods.
The reverse method reverses the order of characters in the StringBuilder. For example, if the contents
of the buffer are "good", the contents after reverse are "doog".