Java Reference
In-Depth Information
individual characters in a string, for comparing strings, for searching strings, and
for creating a copy of a string with all characters changed to uppercase or to
lowercase. Table 9-6 lists the String methods used in the Password class.
Table 9-6
String Methods Used in the Password Class
METHOD
DESCRIPTION
char charAt(int index)
Returns the character at the index specified
boolean equals(Object obj)
Returns true when obj is a String with a matching character
sequence
int hashCode()
Returns a hash code (calculated numeric value) for the string
int length()
Returns the length of the string
String substring(int beginIndex)
Returns as a new String a subset of this string from the
beginning index through the end of the string
String substring(int beginIndex, int endIndex)
Returns as a new String a subset of this string from the
beginning index through the ending index-1
String trim()
Returns as new String a copy of the current string with leading
and trailing white space omitted
As you have learned, the toString() method of the Object class provides
conversion support by returning a string value that represents an object. Because
String objects are immutable, it might appear that trying to concatenate strings,
with or without other non-strings (for example, strX = “abc”+12+“def ”), would
create a series of new String objects, which would not be used again after the
concatenation. This would be true if the concatenation were implemented using
only String objects. String concatenation, however, is implemented with the
StringBuffer class and its append() method, resulting in a more efficient
implementation.
Using the StringBuffer Class
The StringBuffer class implements a mutable sequence of characters —
that is, a string that can be modified. The length and content of the StringBuffer
can be changed at any point in time. Each StringBuffer has an internal buffer
with a particular capacity. As long as the content does not exceed the capacity, no
internal reallocation of the array is necessary. If the capacity of the internal
buffer is exceeded, it is expanded automatically.
A new StringBuffer object may be created with no content, in which case the
capacity is set to 16 by default. A new StringBuffer object also may be created by
using a String (either a reference variable or a string literal) as an argument to
the constructor. In this case, the new StringBuffer will represent the same
sequence of characters as the original String — that is, a copy of the String. The
same constructor can take a concatenation of multiple strings as an argument,
because the result of the concatenation is itself a string.
The two principal operations of a StringBuffer are implemented using the
insert() and append() methods. The insert() method allows any string to be
inserted at any given point within the StringBuffer, moving remaining characters
 
Search WWH ::




Custom Search