Java Reference
In-Depth Information
Comparing Object Values and Classes
In addition to casting, you will often perform three other common tasks that involve
objects:
Comparing objects
n
Finding out the class of any given object
n
Testing to see whether an object is an instance of a given class
n
Comparing Objects
Yesterday, you learned about operators for comparing values—equal, not equal, less than,
and so on. Most of these operators work only on primitive types, not on objects. If you
try to use other values as operands, the Java compiler produces errors.
The exceptions to this rule are the operators for equality— == (equal) and != (not equal).
When applied to objects, these operators don't do what you might first expect. Instead of
checking whether one object has the same value as the other object, they determine
whether both sides of the operator refer to the same object.
To compare instances of a class and have meaningful results, you must implement spe-
cial methods in your class and call those methods.
A good example of this is the String class. It is possible to have two different String
objects that represent the same text. If you were to employ the == operator to compare
these objects, however, they would be considered unequal. Although their contents
match, they are not the same object.
To see whether two String objects have matching values, a method of the class called
equals() is used. The method tests each character in the string and returns true if the
two strings have the same values. Listing 3.5 illustrates this.
LISTING 3.5
The Full Text of EqualsTester.java
1: class EqualsTester {
2: public static void main(String[] arguments) {
3: String str1, str2;
4: str1 = “Free the bound periodicals.”;
5: str2 = str1;
6:
7: System.out.println(“String1: “ + str1);
8: System.out.println(“String2: “ + str2);
9: System.out.println(“Same object? “ + (str1 == str2));
10:
 
Search WWH ::




Custom Search