I have some code like this:
class Foo { public double x; } void test() { Foo foo = new Foo(); // Is this a valid way to test for zero? 'x' hasn't been set to anything yet. if (foo.x == 0) { } foo.x = 0.0; // Will the same test be valid? if (foo.x == 0) { } }
I basically want to avoid a divide-by-zero exception in the future.
Thanks
I think as long as the number has an exact binary fraction representation (like 0) the comparison is perfectly valid. Show activity on this post. You should not use double for such comparision. double creates problem.
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.
equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.
Numeric primitives in class scope are initialized to zero when not explicitly initialized.
Numeric primitives in local scope (variables in methods) must be explicitly initialized.
If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.
if(value != 0) //divide by value is safe when value is not exactly zero.
Otherwise when checking if a floating point value like double
or float
is 0, an error threshold is used to detect if the value is near 0, but not quite 0.
public boolean isZero(double value, double threshold){ return value >= -threshold && value <= threshold; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With