uses toString to create a String from the result.
To build and modify a string, you probably want to use the StringBuilder class. StringBuilder
provides the following constructors:
publicStringBuilder()
Constructs a StringBuilder with an initial value of "" (an empty string)
and a capacity of 16.
publicStringBuilder(int capacity)
Constructs a StringBuilder with an initial value of "" and the given
capacity.
publicStringBuilder(String str)
Constructs a StringBuilder with an initial value copied from str.
publicStringBuilder(CharSequence seq)
Constructs a StringBuilder with an initial value copied from seq.
StringBuilder is similar to String, and it supports many methods that have the same names and
contracts as some String methodsindexOf, lastIndexof, replace, substring. However,
StringBuilder does not extend String nor vice versa. They are independent implementations of
CharSequence.
13.4.1. Modifying the Buffer
There are several ways to modify the buffer of a StringBuilder object, including appending to the end
and inserting in the middle. The simplest method is setCharAt, which changes the character at a specific
position. The following replace method does what String.replace does, except that it uses a
StringBuilder object. The replace method doesn't need to create a new object to hold the results, so
successive replace calls can operate on one buffer:
public static void
replace(StringBuilder str, char oldChar, char newChar) {
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == oldChar)
str.setCharAt(i, newChar);
}
The setLength method truncates or extends the string in the buffer. If you invoke setLength with a
length smaller than the length of the current string, the string is truncated to the specified length. If the length
is longer than the current string, the string is extended with null characters ('\u0000').
There are also append and insert methods to convert any data type to a String and then append the
result to the end or insert the result at a specified position. The insert methods shift characters over to make
room for inserted characters as needed. The following types are converted by these append and insert
methods: