Java Reference
In-Depth Information
Test 2
string3 is now: Too many cooks
string1 is now: Too many cooks
string1 == string3 is true. string1 and string3 point to the same
string
How It Works
The three variables
string1
,
string2
, and
string3
are initialized with the string literals you see. After
executing the assignment statement, the string referenced by
string1
is identical to that referenced by
string3
, but as you see from the output, the comparison for equality in the
if
statement returns
false
because the variables refer to two separate strings. Note that if you were to just initialize
string1
and
string3
with the same string literal,
"Too many cooks"
, only one
String
object would be created,
which both variables would reference. This would result in both comparisons being
true
.
Next you change the value of
string3
so that it refers to the same string as
string1
. The output demon-
strates that the
if
expression has the value
true
, and that the
string1
and
string3
objects do indeed
refer to the same string. This clearly shows that the comparison is
not
between the strings themselves,
but between the references to the strings. So how do you compare the strings?
Comparing Strings for Equality
To compare two
String
variables, that is, to decide whether the strings they reference are equal or not, you
must use the
equals()
method, which is defined for objects of type
String
. For example, to compare the
String
objects referenced by the variables
string1
and
string3
you could write the following statement:
if(string1.equals(string3)) {
System.out.println("string1.equals(string3) is true." +
" so strings are equal.");
}
This calls the
equals()
method for the
String
object referenced by
string1
and passes
string3
as
the argument. The
equals()
method does a case-sensitive comparison of corresponding characters in the
strings and returns
true
if the strings are equal and
false
otherwise. Two strings are equal if they are the
same length, that is, have the same number of characters, and each character in one string is identical to the
corresponding character in the other.
Of course, you could also use the
equals()
method for the string referenced by
string3
to do the com-
parison:
if(string3.equals(string1)) {
System.out.println("string3.equals(string1) is true." +
" so strings are equal.");
}
This is just as effective as the previous version.
To check for equality between two strings ignoring the case of the string characters, you use the method
equalsIgnoreCase()
. Let's put these methods in the context of an example to see them working.