Java Reference
In-Depth Information
Comparing Objects
The Unicode relationships among characters make it easy to sort characters and
strings of characters. If you have a list of names, for instance, you can put them
in alphabetical order based on the inherent relationships among characters in the
character set.
However, you should not use the equality or relational operators to compare
String
objects. The
String
class contains a method called
equals
that returns a
boolean
value that is true if the two strings being compared contain exactly the
same characters and is false otherwise. For example:
if
(name1.equals(name2))
System.out.println ("The names are the same.");
else
System.out.println ("The names are not the same.");
Assuming that
name1
and
name2
are
String
objects, this condition
determines whether the characters they contain are an exact match.
Because both objects were created from the
String
class, they both
respond to the
equals
message. Therefore, the condition could have
been written as
name2.equals(name1),
and the same result would
occur.
It is valid to test the condition
(name1 == name2)
, but that actually tests to
see whether both reference variables refer to the same
String
object. For any
object, the == operator tests whether both reference variables are aliases of each
other (whether they contain the same address). That's different from testing to see
whether two different
String
objects contain the same characters.
Keep in mind that a string literal (such as
"Nathan"
) is a convenience and is
actually a shorthand technique for creating a
String
object. An interesting issue
related to string comparisons is the fact that Java creates a unique object for string
literals only when needed. That is, if the string literal
"Hi"
is used multiple times
in a method, only one
String
object is created to represent it. Therefore, the con-
ditions of both
if
statements in the following code are true:
KEY CONCEPT
The
compareTo
method can be used
to determine the relative order of
strings.
String str = "software";
if
(str == "software")
System.out.println ("References are the same");
if
(str.equals("software"))
System.out.println ("Characters are the same");
The first time the string literal
"software"
is used, a
String
object is created
to represent it and the reference variable
str
is set to its address. Each subsequent
time the literal is used, the original object is referenced.
Search WWH ::
Custom Search