Equality – Basic Elements, Primitive Data Types, and Operators

2.13 Equality

We distinguish between primitive data value equality, object reference equality, and object value equality.

The equality operators have lower precedence than the relational operators, but higher precedence than the assignment operators.

Primitive Data Value Equality: ==, !=

Given that a and b represent operands of primitive data types, the primitive data value equality operators are defined as shown in Table 2.24.

Table 2.24 Primitive Data Value Equality Operators

a == bDetermines whether a and b are equal—that is, have the same primitive value (equality).
a != bDetermines whether a and b are not equal—that is, do not have the same primitive value (inequality).

The equality operator == and the inequality operator != can be used to compare primitive data values, including boolean values. Binary numeric promotion may be applied to the non-boolean operands of these equality operators.

Click here to view code image

int year = 2002;
boolean isEven  = year % 2 == 0;     // true.
boolean compare = ‘1’ == 1;          // false. Binary numeric promotion applied.
boolean test    = compare == false;  // true.

Care must be exercised when comparing floating-point numbers for equality, as an infinite number of floating-point values can be stored only as approximations in a finite number of bits. For example, the expression (1.0 – 2.0/3.0 == 1.0/3.0) returns false, although mathematically the result should be true.

Analogous to the discussion for relational operators, mathematical expressions like a = b = c must be written using relational and logical/conditional operators. Since equality operators have left associativity, the evaluation of the expression a==b==c would proceed as follows: ((a == b) == c). Evaluation of (a == b) would yield a boolean value that is permitted as an operand of a data value equality operator, but (boolean value == c) would be illegal if c had a numeric type. This problem is illustrated in the following examples. The expression at (1) is illegal, but those at (2) and (3) are legal.

Click here to view code image

int a, b, c;
a = b = c = 5;
boolean illegal = a == b == c;               // (1) Illegal.
boolean valid2 = a == b && b == c;           // (2) Legal.
boolean valid3 = a == b == true;             // (3) Legal.