Some
methods below: .insert(...), .append(...), .getChars(...),
setLength(...)
For charAt(...) and indexOf(...), see String’s
methods
charAt(...) and indexOf(...)
■ A StringBuffer’s default capacity is 16 characters, if not specified otherwise in a constructor. However StringBuffer capacities are automatically increased whenever necessary. If they should overflow they just get automatically made longer.
■ The concatenation + symbol is the same as the append(...) method for StringBuffer. i.e
sb = "a" + "b" + "c"; produces the same abc result as the same as the line below
StringBuffer sb = new
StringBuffer(
).append("a").append("b").append("c");
■ StringBuffer does not have an equals( ) method override like String and the wrapper classes do.
So for StringBuffer, == produces the same result as equals( ). Both just look at the object pointer, not at the actual contents.
■ StringBuffer does not have a shorthand form of its constructor, like String does. i.e.
String s = "ABC"; works but
StringBuffer sb = "ABC"; won't compile.
You must say StringBuffer sb = new StringBuffer("ABC");
StringBuffer
.insert( offset, type ) method
■ Works for
many types, including boolean. It
inserts the automatic .valueOf String
representation of the second parm into the StringBuffer at the specified
offset. The offset starts at zero.
■ It updates the original
object’s pointer.
StringBuffer .append( type ) method
■ Works for
many types, including boolean. Adds
their String representation onto the end of this StringBuffer. It’s like doing
an insert(...) at
the end.
■ Updates
the object pointer.
void
.getChars( srcBegin,
srcEnd, char[ ] , dstBegin
) method
■ Just
like String's similar method. It
copies specified chars, from index srcBegin to index SrcEnd-1,
copying them into a pre-existing char array starting at index dstBegin.
■ Will throw
an
IndexOutOfBoundsException if there’s anything wrong with any of the
indexes.
■ This
snippet copies the a and b from the StringBuffer onto the locations of
the 4 and 5 in the original char array, printing the
result 1 2 3 a b 6.
StringBuffer sb = new
StringBuffer(
).append("a").append("b").append("c");
char[ ] ca = {'1', '2',
'3', '4', '5', '6'};
sb.getChars( 0, 2, ca, 3
);
System.out.println(ca);
void .setLength( newlength ) method
■ Resets a
StringBuffer's length by either truncating it (if shorter) or padding it with
\u0000's (if longer).