Dividing a double by zero in Java

siva636 picture siva636 · Jul 25, 2012 · Viewed 8.7k times · Source

Possible Duplicate:
Why doesn't Java throw an Exception when dividing by 0.0?

Why the following statement in Java will not report an ArithmeticException?

double d = 1.0/0;

Answer

blahman picture blahman · Jul 25, 2012

In short: floating point numbers can represent infinity (or even operations that yield values which aren't numbers) so an operation that results in this (e.g. dividing by 0) is valid.

Expanding upon Mohammod Hossain's answer, as well as this question and its accepted answer, an ArithmeticException is thrown "Thrown when an exceptional arithmetic condition has occurred". For integers, dividing by 0 is such a case, but for floating point numbers (floats and doubles) there exist positive and negative representations.

As an example,

public class DivZeroFun {

    public static void main(String args[]) {

        double f = 5.0;
        System.out.println(f / 0);
        double f2 = -5.0;
        System.out.println(f2/0);
    }
}

This code will print "Infinity" and then "-Infinity" as its answers, because "Infinity" is actually an accepted value for floats and doubles that is encoded in Java.

Also, from this forum post:

Floating point representations usually include +inf, -inf and even "Not a Number". Integer representations don't. The behaviour you're seeing isn't unique to Java, most programming languages will do something similar, because that's what the floating point hardware (or low level library) is doing.

and again from the forum post:

Because the IEEE standard for floating point numbers used has defined values for positive and negative infinity, and the special "not a number" case. See the contants in java.lang.Float and java.lang.Double for details.