For this code:
double foo = 100.0;
...
// foo may or may not change value here
...
if (foo == 100) { // will this ever be true?
....
}
Will the if block ever be called? If not, what is the proper way to check whether foo == 100.0?
For this code:
double foo = 100.0;
...
// foo may or may not change value here
...
if (foo == 100) { // will this ever be true?
....
}
Will the if block ever be called? If not, what is the proper way to check whether foo == 100.0?
Just give it a try, mate...
public class Test
{
public static void main(String[] args)
{
double foo = 100.0;
if (foo == 100)
{
System.out.println("true");
}
}
}
Output:
true
Yes, it can be called. The test can be true. If foo is left alone (or reassigned to 100.0), then the comparison will succeed.
But it will only succeed because 100.0 has an exact representation as a double, and the int value 100 will be converted to the same 100.0 double value via a widening primitive conversion.
You are right to be wary of using == to compare double values, because of the fact that some double values are inexact representations of exact literals (e.g. 0.1 is represented inexactly as a double).
The best way to compare double value is to ensure that the values are within a certain (low) tolerance value of each other, as JUnit does:
assertEquals(double expected, double actual, double delta)
This ensures that the expected and actual values are within the tolerance value delta.