Java Reference
In-Depth Information
to the right. For example, given a StringBuffer object, buf, with the current string
contents of book text, the code
buf.insert(4, “mark”);
would alter the string buffer contents to be bookmark text. Using the append()
method adds new characters to the end of the buffer. If the capacity of the
buffer is reached, it is expanded automatically, as indicated earlier. The append()
method also is used in the implementation of String concatenation. For
example, the previously discussed example
strX = “abc”+12+“def”;
is implemented in the String class by creating a new StringBuffer and then
successively appending “abc”, 12, and “def ” to the buffer and then invoking its
toString() method to return a new String with the appended values. Non-string
values, such as 12, are converted to Strings by the corresponding String.valueOf()
method before appending. The String valueOf() method returns a String repre-
senting the value of the argument passed to it. This method is overloaded to
provide a conversion for many different data types.
Although the insert() and append() methods perform the principal opera-
tions, StringBuffer objects also have a number of other useful methods. Table 9-7
lists the StringBuffer methods used in the Password class.
Table 9-7
StringBuffer Methods Used in the Password Class
METHOD
DESCRIPTION
StringBuffer append(int i)
Appends the string or a string representation of the argument to the string
StringBuffer append(String str)
buffer. This method is overloaded to accept a variety of different argument
types.
char charAt(int index)
Returns the character at the specified index in the string buffer.
int length()
Returns the length of the string, in terms of the character count, not the
capacity.
StringBuffer reverse()
Replaces the character sequence contained in the string buffer with the
reverse sequence.
void setCharAt(int index, char ch)
The character in the sequence at the index specified is replaced by the
character ch.
String toString()
Returns a new String object containing the character sequence represented
by the string buffer.
Coding private Helper Methods
When two or more methods must perform the same task, it is likely that the
task should be implemented in another method. The likelihood grows stronger as
the complexity of the task increases. Placing such a task into a separate method
provides two advantages: it lessens the complexity of the current method, and it
minimizes the duplication of code. The second point becomes increasingly impor-
tant when making changes to the code, either for future enhancements or for elim-
ination of errors, or bugs.
 
Search WWH ::




Custom Search