Name

StringBuffer

Synopsis

This class represents a mutable string of characters that can grow or shrink as necessary. Its mutability makes it suitable for processing text in place, which is not possible with the immutable String class. Its resizability and the various methods it implements make it easier to use than a char[ ]. Create a StringBuffer with the StringBuffer( ) constructor. You may pass a String that contains the initial text for the buffer to this constructor, but if you do not, the buffer will start out empty. You may also specify the initial capacity for the buffer if you can estimate the number of characters the buffer will eventually hold.

The methods of this class are synchronized, which makes StringBuffer objects suitable for use by multiple threads. In Java 5.0 and later, when working with a single thread, StringBuilder is preferred over this class because it does not have the overhead of synchronized methods. StringBuilder implements the same methods as StringBuffer and can be used in the same way.

Query the character stored at a given index with charAt( ) and set or delete that character with setCharAt( ) or deleteCharAt( ). Use length( ) to return the length of the buffer, and use setLength( ) to set the length of the buffer, truncating it or filling it with null characters ('\u0000') as necessary. capacity( ) returns the number of characters a StringBuffer can hold before its internal buffer needs to be reallocated. If you expect a StringBuffer to grow ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.