Java Reference
In-Depth Information
In the solution to this recipe, you can see various different techniques for compar-
ing string values. The equals() method is a part of every Java object. The Java
string equals() method has been overridden so that it will compare the values con-
tained within the string rather than the object itself. As you can see from the following
examples that have been extracted from the solution to this recipe, the equals()
method is a safe way to compare strings.
// Comparison is equal
if (one.equals(var1)){
System.out.println ("String one equals var1 using
equals");
}
// Comparison is NOT equal
if (one.equals(two)){
System.out.println ("String one equals two using
equals");
}
The equals() method will first check to see whether the strings reference the
same object using the == operator; it will return true if they do. If they do not refer-
ence the same object, equals() will compare each string character-by-character to
determine whether the strings being compared to each other contain exactly the same
values. What if one of the strings has a different case setting than another? Do they still
compare equal to each other using equals() ? The answer is no, and that is why the
equalsIgnoreCase() method was created. Comparing two values using
equalsIgnoreCase() will cause each of the characters to be compared without
paying attention to the case. The following examples have been extracted from the
solution to this recipe:
// Comparison is NOT equal
if (two.equals(var2)){
System.out.println ("String two equals var2 using
equals");
}
// Comparison is equal
if (two.equalsIgnoreCase(var2)){
System.out.println ("String two equals var2 using
Search WWH ::




Custom Search