Java Reference
In-Depth Information
// Display the contents of the strings
System.out.println("\n\nTest 2");
System.out.println("string3 is now: " + string3);
System.out.println("string1 is now: " + string1);
if(string1 == string3) // Now test for identity
System.out.println("string1 == string3 is true." +
" string1 and string3 point to the same string");
else
System.out.println("string1 == string3 is false." +
" string1 and string3 do not point to the same string");
}
}
We have created two scenarios. In the first, the variables
string1
and
string3
refer to separate strings
that happen to be identical. In the second, they both reference the same string. This will produce the output:
Test 1
string3 is now: Too many cooks
string1 is now: Too many cooks
string1==string3 is false. string1 and string3 do not point to the same string
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
will be 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.
Next we change the value of
string3
so that it refers to the same string as
string1
. The output
demonstrates 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 we 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 method
equals()
, which is defined in the
String
class. This method does a case
sensitive comparison. 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.
To check for equality between two strings ignoring the case of the string characters, you use the method
equalsIgnoreCase()
. Let's put these in the context of an example to see how they work.