Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

StringBuffer Class Properties and Methods

This section describes the StringBuffer class, it properties and methods.

java.lang.StringBuffer: A class represents a mutable sequence of characters stored in an internal buffer. An instance of StringBuffer has 3 important properties:

  • Buffer: The storage where the characters are stored.
  • Capacity: The size of the storage.
  • Length: The number of characters stored in the buffer.

The sequence of characters in the buffer can be manipulated by the following methods:

  • append(): Adding more characters to the end of the sequence.
  • insert(): Inserting more characters at a given position of the sequence.
  • delete(): Removing some characters from the sequence.
  • replace(): Replacing some characters in the sequence.
  • reverse(): Reversing the positions of all characters in the sequence.
  • setLength(): Truncating the sequence or padding the sequence with '\u0000' to make the number of characters equal to the specified value.

The capacity, size of the buffer, may be affected by the following methods:

  • append(), insert(), and replace(): May cause the capacity to be increased, if the current capacity is not large enough to hold the increased number of characters.
  • setLength(): May cause the capacity to be increased, if the current capacity is smaller than the specified value.
  • ensureCapacity(): May cause the capacity to be increased, if the current capacity is smaller than the specified value.

Is there any method that could cause the capacity to be decreased? I don't see any.

Many methods in StringBuffer class return current object. This allows us to write multiple method calls in one statement like this:

   s = s.append("It's ").append{10).append(" o'clock.");

Based on the J2SDK API Specification, an instance of StringBuffer is used by the Sun Java compiler to implement the string concatenation operations. For example, the following statement:

   s = "It's " + 10 + " o'clock.";

will be compiled as:

   s = new StringBuffer().append("It's ").append(10)
      .append(" o'clock.").toString();

Sections in This Chapter

StringBuffer Class Properties and Methods

SimpleStringBuffer - My Implementation of String Buffer

Performance Comparison of String and StringBuffer

Dr. Herong Yang, updated in 2008
StringBuffer Class Properties and Methods