| |
The equals() Method | page 8 of 10 |
The result of == is true if and only if the two variables refer to exactly the same object. You rarely care about that: most likely, you want to compare the contents of two objects. To test whether two objects contain matching data, you'll need to use the equals method. Every Java class supports the equals method, although the definition of "equals" varies from class to class.
String is one of the classes for which the equals method compares the contents of objects, so we can use str1.equals(str2) to test whether str1 and str2 contain the same series of characters.
The equals(String) method does look at the contents of objects. It detects "equivalence." The == operator detects "identity". For example,
String strA; // first object
String strB; // second object
strA = new String("different object, same characters");
strB = new String("different object, same characters");
if (strA == strB)
System.out.println("This will NOT print");
if (strA.equals(strB))
System.out.println("This WILL print");
Run Output:
This WILL print
In this example, there are two objects. Since each object has its own identity, == reports false . Each object contains equivalent data so equals() reports true
|