Java Reference
In-Depth Information
EXAMPLE
String s1;
.
.
.
if ( s1.equals("Hello") )
System.out.println("The string is Hello.");
else
System.out.println("The string is not Hello.");
PITFALL: Using == with Strings
Although == correctly tests two values of a primitive type, such as two numbers, to see
whether they are equal, it has a different meaning when applied to objects, such as
objects of the class String . 2 Recall that an object is something whose type is a class,
such as a string. All strings are in the class String (that is, are of type String ), so ==
applied to two strings does not test to see whether the strings are equal. Instead, this
tests whether two strings refer to the same object. We'll discuss references in Chapter
15. To test two strings (or any two objects) to see if they have equal values, you should
use the method equals rather than ==. For example, suppose s1 and s2 are String
variables that have been given values, and consider the statement
if (s1.equals(s2))
System.out.println("They are equal strings.");
else
System.out.println("They are not equal strings.");
If s1 and s2 name strings that contain the same characters in the same order, then
the output will be
They are equal strings.
The notation may seem a bit awkward at first, because it is not symmetric between
the two things being tested for equality. The two expressions
s1.equals(s2)
s2.equals(s1)
are equivalent.
(continued)
2
2 When applied to two strings (or any two objects), == tests to see if they are stored in the same mem-
ory location, but we will not discuss that until Chapter 4. For now, we need only note that == does
something other than test for the equality of two strings.
Search WWH ::




Custom Search