Object Reference Equality: ==, !=
The equality operator == and the inequality operator != can be applied to reference variables to test whether they refer to the same object. Given that r and s are reference variables, the reference equality operators are defined as shown in Table 2.25.
Table 2.25 Reference Equality Operators
r == s | Determines whether r and s are equal—that is, have the same reference value and therefore refer to the same object (also called aliases) (equality). |
r != s | Determines whether r and s are not equal—that is, do not have the same reference value and therefore refer to different objects (inequality). |
The operands must be cast compatible: It must be possible to cast the reference value of the one into the other’s type; otherwise a compile-time error will result. Casting of references is discussed in §5.8, p. 261.
Pizza pizzaA = new Pizza(“Sweet&Sour”); // new object
Pizza pizzaB = new Pizza(“Sweet&Sour”); // new object
Pizza pizzaC = new Pizza(“Hot&Spicy”); // new object
String banner = “Come and get it!”; // new object
boolean test = banner == pizzaA; // (1) Compile-time error
boolean test1 = pizzaA == pizzaB; // false
boolean test2 = pizzaA == pizzaC; // false
pizzaA = pizzaB; // Denote the same object; are aliases
boolean test3 = pizzaA == pizzaB; // true
The comparison banner == pizzaA at (1) is illegal because the String and Pizza types are incompatible operand types as the reference value of one type cannot be cast to the other type. The values of test1 and test2 are false because the three references denote different objects, regardless of the fact that pizzaA and pizzaB are both sweet and sour pizzas. The value of test3 is true because now both pizzaA and pizzaB denote the same object.
The equality and inequality operators are applied to object references to check whether two references denote the same object. The state of the objects that the references denote is not compared. This is the same as testing whether the references are aliases, meaning that they denote the same object.
The null literal can be assigned to any reference variable, and the reference value in a reference variable can be compared for equality with the null literal. The comparison can be used to avoid inadvertent use of a reference variable that does not denote any object.
if (objRef != null) {
// … use objRef …
}
Note that only when the type of both operands is either a reference type or the null type do these operators test for object reference equality. Otherwise, they test for primitive data equality (see also §8.3, p. 432). In the following code snippet, binary numeric promotion involving unboxing is performed at (1):
Integer iRef = 10;
boolean b1 = iRef == null; // Object reference equality
boolean b2 = iRef == 10; // (1) Primitive data value equality
boolean b3 = null == 10; // Compile-time error!