The StringBuffer class

 

Overview

Unlike the String class which can only be used to instantiate an immutable object, the StringBuffer class can be used to instantiate a mutable object for storing and processing a string of characters. The string's length and contents may change as characters are appended, inserted, replaced, and removed from the StringBuffer object. And, if additional memory is needed for a StringBuffer object, it is automatically obtained.

 

The StringBuffer class

Object 

\

StringBuffer 

StringBuffer jobTitle = new StringBuffer("programmer");

will instantiate a StringBuffer having a value of "programmer" and assign it to jobTitle. The initial capacity of the object will be the length of the string plus 16 characters (26 characters in this example).

The default constructor accepts no parameters. For example,

StringBuffer buffer = new StringBuffer();

will instantiate a StringBuffer object having no string value and an initial capacity of 16 characters.

Yet another constructor accepts a single int parameter for specifying the initial character capacity of the object. For example,

StringBuffer message = new StringBuffer(100);

will instantiate a StringBuffer object having no string value and an initial capacity of 100 characters.

Method

Usage

charAt()

Returns the character at the specified index within the string where the first character has an index of 0

length()

Returns the character length of this string

substring()

Extracts a substring from this string to create a String object

Method

Usage

append()

Appends the string representation of the parameter to this StringBuffer object (overloaded)

capacity()

Returns the character capacity of this StringBuffer object

delete()

Removes a specified substring from this StringBuffer object

deleteCharAt()

Removes a character from the specified index location within this StringBuffer object

insert()

Inserts the string representation of the parameter into this StringBuffer object (overloaded)

replace()

Replaces a specified substring within this StringBuffer object with another substring

reverse()

Reverses all characters within this StringBuffer object

setCharAt()

Replaces a specified character with in this StringBuffer object

toString()

Creates a String object from the contents of this StringBuffer object 

For more detailed information, consult Java API documentation.

"Value is " + xyz

is processed by the compiler as

new StringBuffer().append("Value is ").append(xyz).toString()

The steps in evaluating this expression are:

  1. A new StringBuffer object being instantiated

  2. The string "Value is" being appended to the StringBuffer object

  3. The string representation of variable xyz being appended to the StringBuffer object

  4. The StringBuffer object being converted to a String object

While StringBuffer does not override its inherited equals() method, String does. So, to test two StringBuffer objects for equality, you must compare their String equivalents. The corrected code for the above example is

StringBuffer x = new StringBuffer("abc");
StringBuffer y = new StringBuffer("abc");
if (x.toString().equals(y.toString()))
  System.out.println("They have the same value");
else
  System.out.println("They have different values");

where the toString() method of each StringBuffer object is called to obtain its String equivalent.

Similarly, the StringBuffer class does not have a compareTo() method. To compare two StringBuffer objects to determine which comes first alphabetically, you must convert each object to its String equivalent and use the compareTo() method of the String class.

 

Sample program

The following menu-driven program allows a user to perform a variety of actions on a string that is implemented as a StringBuffer object.

public class App {
  public static void main(String[] args) {

    // Variables.

    StringBuffer buffer = new StringBuffer();
    byte choice;

    // Loop to process one string operation.

    do {

      // Display the current string, the menu, and read the user's menu
      // selection.

      Utility.separator(70, '~');
      System.out.println("\t       00000000001111111111222222222233333333334");
      System.out.println("\t       01234567890123456789012345678901234567890");
      Utility.skip();
      System.out.println("\tValue: " + buffer);
      Utility.skip();
      System.out.print("1 - Append ");
      System.out.print("2 - Insert ");
      System.out.print("3 - Reverse ");
      System.out.print("4 - Clear ");
      System.out.print("5 - Exit");
      Utility.skip(2);
      System.out.print("Enter your selection: ");
      choice = Keyboard.readByte();

      // Process the user's menu selection.

      switch (choice) {

        // This case asks the user to enter a string and appends it to
        // the current string.

        case 1:
          Utility.separator(70, '~');
          System.out.print("String to append: ");
          buffer.append(Keyboard.readString());
          break;

        // This case asks the user for a string to insert and the character
        // index of the insertion point. If the index is valid, the string
        // is inserted. Otherwise, an error message is displayed.

        case 2:
          Utility.separator(70, '~');
          System.out.print("String to insert: ");
          String temp = Keyboard.readString();
          System.out.print("Character index of insertion point: ");
          byte index = Keyboard.readByte();
          if (index >= 0 && index < buffer.length()) {
            buffer.insert(index, temp);
          }
          else {
            System.out.println("\tInvalid character index");
          }
          break;

        // This case reverses all the characters within the string.

        case 3:
          buffer.reverse();
          break;

        // This case deletes all the characters from the string.

        case 4:
          buffer.delete(0, buffer.length());
          break;

        // This is the exit case. It does absolutely nothing.

        case 5:
          break;

        // This default case handles an invalid menu selection.

        default:
          Utility.separator(70, '~');
          System.out.println("\tInvalid selection");
          break;
      }
    } while (choice != 5);  // Loop unless the user wants to exit.
  }
}

Notes:

  1. The sample declares a StringBuffer object referenced by buffer which is initially empty.

  2. Each time the menu appears, the current value of the string is displayed along with a guide that shows the index position of each character within the string.

  3. The switch statement is used to process the user's menu choice.

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
StringBuffer x = "abc";
StringBuffer y = new StringBuffer("def");
System.out.println(x + y);
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compilation will succeed. The message "abcdef" will be displayed.

  5. Compilation will succeed.  The message "abc def" will be displayed.

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
StringBuffer buffer = new StringBuffer(5);
buffer.append("Hello World!");
System.out.println(buffer);
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compilation will succeed.  The string "Hello" will be displayed.

  5. Compilation will succeed.  The string "Hello World!" will be displayed.

  1. Assuming that all unseen code is correct, what will be displayed from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
4
5
6
String s = "xyz";
StringBuffer sb = new StringBuffer("xyz");
if (s.equals(sb))
  System.out.println("They are the same");
if (sb.equals(s))
  System.out.println("They are alike");
  1. Statements 3 and 5 will not compile because s and sb are of different types

  2. Compilation will succeed but nothing will be displayed

  3. They are the same

  4. They are alike

  5. They are the same
    They are alike

  1. Assume that x is the object reference of a StringBuffer object having the string value "abc". Which of the statements below will be true of executing the following?  (choose two)

x.deleteCharAt(1).reverse();

  1. x will reference the same StringBuffer object

  2. x will reference a different StringBuffer object

  3. the string value of the object referenced by x will be "ca"

  4. the string value of the object referenced by x will be "cb"

  5. the string value of the object referenced by x will be "c a"