Java Reference
In-Depth Information
Single-character strings should not be replaced with character constants;
Exercise 2.7 asks you to show why. Note that operator
+
is left-associative,
and thus
"a" + 1 + 2 // Generates "a12"
1 + 2 + "a" // Generates "3a"
1 + ( 2 + "a" ) // Generates "12a"
Also, operator
+=
is provided for the
String
. The effect of
str+=exp
is the
same as
str=str+exp
. Specifically, this means that
str
will reference the newly
constructed
String
generated by
str+exp
.
2.3.3
comparing strings
Since the basic assignment operator works for
String
s, it is tempting to
assume that the relational and equality operators also work. This is not
true.
In accordance with the ban on operator overloading, relational operators
(
<
,
>
,
<=
, and
>=
) are not defined for the
String
type. Further,
==
and
!=
have the
typical meaning for reference variables. For two
String
objects
lhs
and
rhs
,
for example,
lhs==rhs
is
true
only if
lhs
and
rhs
refer to the same
String
object. Thus, if they refer to different objects that have identical contents,
lhs==rhs
is
false
. Similar logic applies for
!=
.
To compare two
String
objects for equality, we use the
equals
method.
lhs.equals(rhs)
is
true
if
lhs
and
rhs
reference
String
s that store identical
values.
A more general test can be performed with the
compareTo
method.
lhs.compareTo(rhs)
compares two
String
objects,
lhs
and
rhs
. It returns a neg-
ative number, zero, or a positive number, depending on whether
lhs
is lexico-
graphically less than, equal to, or greater than
rhs
, respectively.
Use
equals
and
compareTo
to per-
form string
comparison.
2.3.4
other
String
methods
The length of a
String
object (an empty string has length zero) can be
obtained with the method
length
. Since
length
is a method, parentheses are
required.
Two methods are defined to access individual characters in a
String
. The
method
charAt
gets a single character by specifying a position (the first posi-
tion is position 0). The method
substring
returns a reference to a newly con-
structed
String
. The call is made by specifying the starting point and the first
nonincluded position.
Here is an example of these three methods:
Use
length
,
charAt
,
and
substring
to
compute string
length, get a single
character, and get
a substring,
respectively.
Search WWH ::
Custom Search