|
JavaFAQ Home » Java Lessons by Jon Huhtala

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.
-
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.
|
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.
- 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:
-
A new StringBuffer object being instantiated
-
The string "Value is" being appended to the StringBuffer object
-
The string representation of variable xyz being appended to the
StringBuffer object
-
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("
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:
-
The sample declares a StringBuffer object
referenced by buffer
which is initially empty.
-
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.
-
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
-
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); |
-
Compilation will fail at
line 1
-
Compilation will fail at
line 2
-
Compilation will succeed
but a runtime error will occur
-
Compilation will succeed.
The message "abcdef" will be
displayed.
-
Compilation will
succeed. The message "abc def"
will be displayed.
-
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); |
-
Compilation will fail at
line 1
-
Compilation will fail at
line 2
-
Compilation will succeed
but a runtime error will occur
-
Compilation will
succeed. The string "Hello"
will be displayed.
-
Compilation will
succeed. The string "Hello
World!" will be displayed.
-
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"); |
-
Statements 3 and 5 will
not compile because s
and sb are of different
types
-
Compilation will succeed
but nothing will be displayed
-
They are the same
-
They are alike
-
They are the same They are alike
-
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();
-
x will reference the same StringBuffer object
-
x will reference a different StringBuffer object
-
the string value of the
object referenced by x will be "ca"
-
the string value of the
object referenced by x will be "cb"
-
the string value of the
object referenced by x will be "c a" Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|