4.9 StringBuffer in Java

A StringBuffer object is similar to a String object but is more efficient when you are repeatedly appending characters to a string. Unlike a String, a StringBuffer is mutable so its contents can be modified. The nonobject-oriented syntactical sugar provided by Strings in initialization and concatenation does not apply to StringBuffer objects. For example, the statement

StringBuffer textbuf = "A circle of ";

is illegal. A valid statement would be

StringBuffer textbuf = new StringBuffer("A circle of ");

The statement

textbuf = textbuf + "radius ";

is also illegal. We need to make use of the java.lang.StringBuffer.append method. The following statement is legal:

textbuf.append("radius ");

To modify a character within a StringBuffer object,use the java.lang.StringBuffer. setCharAt method. For example, the statement

textbuf.setCharAt(3, 'Z');

sets the fourth character (counting starts at zero) of textbuf to 'Z'.

No comments:

Post a Comment