Java Reference
In-Depth Information
In this example, you tried to test whether the three variables i , j and k have the same value, and the expression
(i == j == k) resulted in an error. Why did you get the error? The expression (i == j == k) is evaluated as follows:
First, i == j is evaluated in expression i == j == k. Since both i and j have the same value, which
is 15, the expression i == j returns true.
The first step reduced the expression i == j == k to true == k. This is an error because the
operands of == operator are of boolean and int types. You cannot mix boolean and numeric
types operands with the equality operator.
The following rules apply when the operands of the equality operator are floating-point types.
Rule #1
Both negative zero (-0.0) and positive zero (0.0) are considered equal. Recall that -0.0 and 0.0 are stored
differently in memory.
double d1 = 0.0;
double d2 = -0.0;
boolean b = (d1 == d2); // Assigns true to b
Rule #2
A positive infinity is equal to another positive infinity. A negative infinity is equal to another negative infinity.
However, a positive infinity is not equal to a negative infinity.
double d1 = Double.POSITIVE_INFINITY;
double d2 = Double.NEGATIVE_INFINITY;
boolean b1 = (d1 == d2); // Assigns false to b1
boolean b2 = (d1 == d1); // Assigns true to b2
Rule #3
If either operand is NaN , the equality test returns false.
double d1 = Double.NaN;
double d2 = 5.5;
boolean b = (d1 == d2); // Assigns false to b
Note that even if both the operands are NaN , the equality operator will return false.
d1 = Double.NaN;
d2 = Double.NaN;
b = (d1 == d2); // Assigns false to b
How do you test whether the value stored in a float or double variable is NaN ? If you write the following piece of
code to test for the value of a double variable d1 being NaN , it will always return false :
double d1 = Double.NaN;
boolean b = (d1 == Double.NaN); // Assigns false to b. Incorrect way
 
Search WWH ::




Custom Search