Java Reference
In-Depth Information
So when do you use StringBuffer objects rather than String objects? StringBuffer objects
come into their own when you are transforming strings - adding, deleting, or replacing substrings in a
string. Operations will be faster and easier using StringBuffer objects. If you have static strings,
which you occasionally need to concatenate, then String objects will be the best choice. Of course, if
you want to you can mix the use of both in the same program.
Creating StringBuffer Objects
You can create a StringBuffer object that contains a given string with the statement:
StringBuffer aString = new StringBuffer("A stitch in time");
This declares a StringBuffer object, aString , and initializes it with the string A stitch in time .
When you are initializing a StringBuffer object, you must use this syntax, with the keyword new ,
the StringBuffer class name, and the initializing value between parentheses. You cannot just use the
string as the initializing value as we did with String objects. This is because there is rather more to a
StringBuffer object than just the string that it contains initially, and, of course, a string literal is a
String object by definition.
You can just create the StringBuffer variable, in much the same way as you created a
String variable:
StringBuffer myString = null;
This variable does not refer to anything until you initialize it with a defined StringBuffer object. For
example, you could write:
myString = new StringBuffer("Many a mickle makes a muckle");
which will initialize it with the string specified. You can also initialize a StringBuffer variable with
an existing StringBuffer object:
myString = aString;
Both myString and aString will now refer to a single StringBuffer object.
The Capacity of a StringBuffer Object
The String objects that we have been using each contain a fixed string, and memory is allocated to
accommodate however many Unicode characters are in the string. Everything is fixed so memory usage
is not a problem. A StringBuffer object is a little different. It contains a block of memory called a
buffer , which may or may not contain a String , and if it does, the string need not occupy all of the
buffer. Thus the length of a string in a string object can be different from the length of the buffer. The
length of the buffer is referred to as the capacity of the StringBuffer object.
Once you have created a StringBuffer object, you can find the length of the string it contains, by
using the length() method for the object:
Search WWH ::




Custom Search