Java Reference
In-Depth Information
This statement deletes the substring
"the "
from
phrase
, so it then contains the string
"When bats come
in"
.
You can completely reverse the sequence of characters in a
StringBuffer
object with the
reverse()
method. For example, if you define the object with the declaration
StringBuffer palindrome = new StringBuffer("so many dynamos");
you can then transform it with the statement:
palindrome.reverse();
which results in
palindrome
containing the useful phrase “
somanyd ynam os
”.
Creating a String Object from a StringBuffer Object
You can produce a
String
object from a
StringBuffer
object by using the
toString()
method of the
StringBuffer
class. This method creates a new
String
object and initializes it with the string contained in
the
StringBuffer
object. For example, to produce a
String
object containing the proverb that you created
in the previous section, you could write:
String saying = proverb.toString();
The object
saying
contains
"Many hands make light work"
.
The
toString()
method is used extensively by the compiler together with the
append()
method to im-
plement the concatenation of
String
objects.
Suppose you have the following strings defined:
String str1 = "Many", str2=" hands", str3=" make", str4=" light", str5=" work.";
When you write a statement such as
String saying = str1 + str2 + str3 + str4 + str5;
the compiler implements this as:
String saying = new StringBuffer().append(str1).append(str2).
append(str3).append(str4).
append(str5).toString();
The expression to the right of the
=
sign is executed from left to right, so the segments of the string encap-
sulated by the objects are appended to the
StringBuffer
object that is created until finally the
toString()
method is invoked to convert it to a
String
object.
String
objects can't be modified, so any alteration or
extension of a
String
object involves the use of a
StringBuffer
object, which can be changed.
It's time to see a
StringBuffer
object in action.