Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 18: The StringBuffer class

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

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

  • Is part of the java.lang package so no import statement is needed

  • Is an extension of the Object class. This means a StringBuffer is an Object and inherits all the features of the Object class. The implications of class inheritance will be covered in a later lesson.

Object

StringBuffer
  • Has many similarities to the String class, but the string it encapsulated can be modified. At any point in time a StringBuffer object contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

  • Has a capacity. As long as the length of the character sequence contained in a StringBuffer object does not exceed the capacity, no additional memory is required. If the character sequence overflows the object's capacity, additional memory is automatically obtained and the capacity expanded.

  • Has several overloaded constructor methods. The most frequently used will instantiate a StringBuffer object from a String object. For example,

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.

  • Has several methods that are virtually the same as those of the String class. These are:

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

  • Has numerous methods that differ from like-named methods of the String class or have no String class equivalent. The most frequently used are:

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.
  • Is used by the compiler to implement the '+' operator to concatenate strings. For example, the expression

"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

  • Has a useless equals() method inherited from the Object class. The default behavior of the inherited method is to compare object references and NOT object values. It acts the same as the "==" operator.

    This can trick an inexperienced programmer. The following code, for example, will say that the objects have different values:

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

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(" 00000000001111111111222222222233333333334");
System.out.println(" 01234567890123456789012345678901234567890");
Utility.skip();
System.out.println(" Value: " + 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(" Invalid 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(" Invalid 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"


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy