THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

differentSign();


The equality operators can also be applied to reference types. The expression ref1==ref2 is true if the two
references refer to the same object or if both are null, even if the two references are of different declared
types. Otherwise, it is false.


The equality operators test for reference identity, not object equivalence. Two references are identical if they
refer to the same object; two objects are equivalent if they logically have the same value. Equivalence is tested
with the equals method defined by Object, which you should override in classes for which equivalence
and identity are different. Object.equals assumes an object is equal only to itself. For example, the
String class overrides equals to test whether two String objects have the same contentssee Chapter 13.


9.2.3. Logical Operators


The logical operators combine boolean expressions to yield boolean values and provide the common
operations of boolean algebra:


& logical AND

| logical inclusive OR

^ logical exclusive or (XOR)

! logical negation

&& conditional AND

|| conditional OR

A "logical AND" is true if and only if both its operands are true, while a "logical OR" is true if and only if
either of its operands are true. The "exclusive OR" operator yields true if either, but not both, of its operands is
truewhich is the same as testing the equality of the two operands, so we can rewrite our earlier example as:


if ((x < 0) ^ (y < 0))
differentSign();
else
sameSign();


The unary operator! negates, or inverts, a boolean, so !true is the same as false and !false is the
same as true.


Boolean values are normally tested directlyif x and y are booleans, the code


if (x || !y) {
// ...
}


is considered cleaner than the equivalent, but more verbose

Free download pdf