Java String Buffers

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

Example

public class StringBuffer1 {
   public static void main( String args[] )
   {
	   test1();
	   test2();
	   test3();
	   test4();
   }

   public static void show(String s)
   {
	   System.out.println(s);
   }

StringBuffer constructors, length, and capacity methods

   public static void test1() {
	   StringBuffer buf1, buf2, buf3;

	   buf1 = new StringBuffer();
	   buf2 = new StringBuffer( 10 );
	   buf3 = new StringBuffer( "Hello, how are you?" );

	   show( "buf1 = " + "\"" + buf1.toString() + "\"" );
	   show( "\tlength " + buf1.length() + "\tcapacity " + buf1.capacity());
	   show( "buf2 = " + "\"" + buf2.toString() + "\"" );
	   show( "\tlength " + buf2.length() + "\tcapacity " + buf2.capacity());
	   show( "buf3 = " + "\"" + buf3.toString() + "\"" );
	   show( "\tlength " + buf3.length() + "\tcapacity " + buf3.capacity());

	   buf3.ensureCapacity(75);
	   buf3.setLength(10);
	   show( "\nChange buf3:");
	   show( "buf3 = " + "\"" + buf3.toString() + "\"" );
	   show( "\tlength " + buf3.length() + "\tcapacity " + buf3.capacity());
   }

test1 output:

buf1 = ""
	length 0	capacity 16
buf2 = ""
	length 0	capacity 10
buf3 = "Hello, how are you?"
	length 19	capacity 35

Change buf3:
buf3 = "Hello, how"
	length 10	capacity 75

Methods charAt, setCharAt, getChars, and reverse

   // The charAt, setCharAt, getChars, and reverse methods
   public static void test2() {
	   StringBuffer buf = new StringBuffer( "hello there" );

	   show( "\nbuf = " + buf.toString() );
	   show( "Character at 0: " + buf.charAt( 0 ) );
	   show( "Character at 4: " + buf.charAt( 4 ) );

	   char charArray[] = new char[ buf.length() ];
	   buf.getChars( 0, buf.length(), charArray, 0 );
	   String output = "\nThe characters are: ";

	   for ( int i = 0; i < charArray.length; ++i )
		   output += charArray[ i ];
	   show(output);

	   buf.setCharAt( 0, 'H' );
	   buf.setCharAt( 6, 'T' );
	   show( "modified buf = " + buf.toString() );

	   buf.reverse();
	   show( "buf.reverse() = " + buf.toString() );
   }

test2 output:

buf = hello there
Character at 0: h
Character at 4: o

The characters are: hello there
modified buf = Hello There
buf.reverse() = erehT olleH

StringBuffer append methods

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

   static public void test3() {
	   // append methods of the StringBuffer class.
	   Object o = "hello"; 
	   String s = "good bye";  
	   char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
	   boolean b = true;
	   char c = 'Z';
	   int i = 7;
	   long l = 10000000;
	   float f = 2.5f;
	   double d = 33.333;
	   StringBuffer buf = new StringBuffer();

	   buf.append( o );
	   buf.append( "  " );
	   buf.append( s );
	   buf.append( "  " );
	   buf.append( chars );
	   buf.append( "  " );
	   buf.append( chars, 0, 3 );
	   buf.append( "  " );
	   buf.append( b );
	   buf.append( "  " );
	   buf.append( c );
	   buf.append( "  " );
	   buf.append( i );
	   buf.append( "  " );
	   buf.append( l );
	   buf.append( "  " );
	   buf.append( f );
	   buf.append( "  " );
	   buf.append( d );

	   show("\nResult of appending various objects to buf:");
	   show(buf.toString());
   }

test 3 output:

Result of appending various objects to buf:
hello  good bye  abcdef  abc  true  Z  7  10000000  2.5  33.333

StringBuffer objects and their append methods are used by the compiler to implement the + and += operators for String concatenation. For example,

	String s = "BC" + 12;
is actually performed as
	s = new StringBuffer("BC").append(12).toString();
The statement
	s += "!";
is performed as
	s = new StringBuffer(s).append("!").toString();
Finally, the code:

     x = "a" + 4 + "c"
 

is compiled to the equivalent of:

     x = new StringBuffer().append("a").append(4).append("c")
                           .toString()
 
which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

StringBuffer Insertion and Deletion Methods

   public static void test4() {
	   Object o = "hello";  
	   String s = "good bye";  
	   char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
	   boolean b = true;
	   char c = 'K';
	   int i = 7;
	   long l = 10000000;
	   float f = 2.5f;
	   double d = 33.333;
	   StringBuffer buf = new StringBuffer();

	   buf.insert( 0, o );
	   buf.insert( 0, "  " );
	   buf.insert( 0, s );
	   buf.insert( 0, "  " );
	   buf.insert( 0, charArray );
	   buf.insert( 0, "  " );
	   buf.insert( 0, b );
	   buf.insert( 0, "  " );
	   buf.insert( 0, c );
	   buf.insert( 0, "  " );
	   buf.insert( 0, i );
	   buf.insert( 0, "  " );
	   buf.insert( 0, l );
	   buf.insert( 0, "  " );
	   buf.insert( 0, f );
	   buf.insert( 0, "  " );
	   buf.insert( 0, d );

	   show( "\nbuf after inserts:" );
	   show( buf.toString() );

	   buf.deleteCharAt( 10 );     // delete 5 in 2.5
	   buf.delete( 2, 6 );         // delete .333 in 33.333

	   show( "\nbuf after deletes:" );
	   show( buf.toString() );
   }

test 4 output:

buf after inserts:
33.333  2.5  10000000  7  K  true  abcdef  good bye  hello

buf after deletes:
33  2.  10000000  7  K  true  abcdef  good bye  hello

StringBuffer Methods

length

public int length()
Returns the length (character count) of this string buffer.

Returns:
the length of the sequence of characters currently represented by this string buffer.


capacity

public int capacity()
Returns the current capacity of the String buffer. The capacity is the amount of storage available for newly inserted characters; beyond which an allocation will occur.

Returns:
the current capacity of this string buffer.


ensureCapacity

public void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum. If the current capacity of this string buffer is less than the argument, then a new internal buffer is allocated with greater capacity. The new capacity is the larger of: If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

Parameters:
minimumCapacity - the minimum desired capacity.


setLength

public void setLength(int newLength)
Sets the length of this String buffer. This string buffer is altered to represent a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character ''. In other words, if the newLength argument is less than the current length of the string buffer, the string buffer is truncated to contain exactly the number of characters given by the newLength argument.

If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended to the string buffer so that length becomes the newLength argument.

The newLength argument must be greater than or equal to 0.

Parameters:
newLength - the new length of the buffer.
Throws:
IndexOutOfBoundsException - if the newLength argument is negative.


charAt

public char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned. The first character of a string buffer is at index 0, the next at index 1, and so on, for array indexing.

The index argument must be greater than or equal to 0, and less than the length of this string buffer.

Parameters:
index - the index of the desired character.
Returns:
the character at the specified index of this string buffer.
Throws:
IndexOutOfBoundsException - if index is negative or greater than or equal to length().


getChars

public void getChars(int srcBegin,
                     int srcEnd,
                     char[] dst,
                     int dstBegin)
Characters are copied from this string buffer into the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1. The total number of characters to be copied is srcEnd-srcBegin. The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

 dstbegin + (srcEnd-srcBegin) - 1
 

Parameters:
srcBegin - start copying at this offset in the string buffer.
srcEnd - stop copying at this offset in the string buffer.
dst - the array to copy the data into.
dstBegin - offset into dst.
Throws:
NullPointerException - if dst is null.
IndexOutOfBoundsException - if any of the following is true:
  • srcBegin is negative
  • dstBegin is negative
  • the srcBegin argument is greater than the srcEnd argument.
  • srcEnd is greater than this.length(), the current length of this string buffer.
  • dstBegin+srcEnd-srcBegin is greater than dst.length


setCharAt

public void setCharAt(int index,
                      char ch)
The character at the specified index of this string buffer is set to ch. The string buffer is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.

The offset argument must be greater than or equal to 0, and less than the length of this string buffer.

Parameters:
index - the index of the character to modify.
ch - the new character.
Throws:
IndexOutOfBoundsException - if index is negative or greater than or equal to length().


append

public StringBuffer append(Object obj)
Appends the string representation of the Object argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

Parameters:
obj - an Object.
Returns:
a reference to this StringBuffer object.


append

public StringBuffer append(String str)
Appends the string to this string buffer.

The characters of the String argument are appended, in order, to the contents of this string buffer, increasing the length of this string buffer by the length of the argument. If str is null, then the four characters "null" are appended to this string buffer.

Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the append method. Then the character at index k in the new character sequence is equal to the character at index k in the old character sequence, if k is less than n; otherwise, it is equal to the character at index k-n in the argument str.

Parameters:
str - a string.
Returns:
a reference to this StringBuffer.


reverse

public StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.

Returns:
a reference to this object..


toString

public String toString()
Converts to a string representing the data in this string buffer. A new String object is allocated and initialized to contain the character sequence currently represented by this string buffer. This String is then returned. Subsequent changes to the string buffer do not affect the contents of the String.

Returns:
a string representation of the string buffer.


Maintained by John Loomis, last updated 15 June 2000