Java Reference
In-Depth Information
The Equality Operators
The == (equal to) and != (not equal to) operators are referred to as the equality operators.
The equality operators can be used in the following three situations, all of which return a
boolean :
The two operands are numerical primitive types.
The two operands are boolean types.
The two operands are references types or null types.
This implies that you cannot compare a byte to a boolean , or an int to a reference type.
The two operands must be compatible. If one operand is a larger type, then the smaller
type is promoted before the comparison. For example, you can compare an int to a float ;
the int is promoted to a float and a fl oating-point comparison is made. You can compare
a char to an int : the char is promoted to an int and integer equality is performed.
Let's look at some uses of the equality operators. Examine the following code and try to
determine its output:
6. int x = 57;
7. float f = 57.0F;
8. double d = 5.70;
9. boolean b = false;
10.
11. boolean one = x == 57;
12. System.out.println(one);
13. boolean two = (f != d);
14. System.out.println(two);
15. boolean three = (b = true);
16. System.out.println(three);
Lines 12 and 14 both print out true . The order of operations on line 11 ensures that x
is compared to 57 before the assignment to one , even though parentheses would have made
that statement easier to read (as in line 13). If you glanced over this code too quickly, you
may think that line 16 prints out false , but the actual output is true . On line 15,
(b = true) is an assignment, not a test for equality. Following the order of parentheses, b
is set to true fi rst, then three = b is evaluated, which sets three equal to true . The output
of these statements is
true
true
true
The equality operators can also be evaluated on reference types. It is important to
understand that evaluating == and != on two references compares the references, not the
objects they point to. Two references are equal if and only if they point to the same object
(or both point to null ); otherwise, the two references are not equal.
Search WWH ::




Custom Search