34

I'm just curious about this:

When evaluating 1/0 in Java, the following exception occurs:

Exception in thread "main" java.lang.ArithmeticException: / by zero at Foo.main(Foo.java:3)

But 1/0.0 is evaluated to Infinity.

public class Foo {
    public static void main (String[] args) {
        System.out.println(1/0.0);
    }
}

Why does this happen?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Fábio Perez
  • 23,850
  • 22
  • 76
  • 100

5 Answers5

34

That's because integers don't have values for +/-Inf, NaN, and don't allow division by 0, while floats do have those special values.

ninjalj
  • 42,493
  • 9
  • 106
  • 148
13

1/0 is a division of two ints, and throws an exception because you can't divide by integer zero. However, 0.0 is a literal of type double, and Java will use a floating-point division. The IEEE floating-point specification has special values for dividing by zero (among other thing), one of these is double.Infinity.

If you're interested in details, the floating-point spec (which is often cryptic) has a page at Wikipedia: http://en.wikipedia.org/wiki/IEEE_754-2008, and its full text can be also read online: http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933.

Kristóf Marussy
  • 1,202
  • 8
  • 18
  • 3
    Unfortunately, Java does not allow setting up IEEE 754-2008 traps. If you write 1/0.0 in your code, it's obvious where the Infinity comes from, but if you get a NaN from a function that does lots of numerics, [it's not simple to find out what exactly went wrong](http://stackoverflow.com/questions/2140501/java-maths-testing-for-nan). – Jouni K. Seppänen Mar 13 '11 at 19:14
2

1/0 is integer division, 1/0.0 is floating point division - Floats can represent invalid values, integers can't.

Erik
  • 88,732
  • 13
  • 198
  • 189
1

The IEEE has defined certain standards for floating point numbers which include definitions for "Not a Number" and positive and negative infinity. These do not apply to integers.

See http://steve.hollasch.net/cgindex/coding/ieeefloat.html

The reason for these special cases in basically rounding errors. Floating point numbers are often always truncated because they are never exact. Integers, on the other hand, are always exact.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
0

fetestexcept and feenableexcept

It is worth noting that the underlying CPU hardware can detect the specific case of 0.0 / 0.0, and:

  • set some flag bits, which can be queried with ANSI C fetestexcept(FE_ALL_EXCEPT) == FE_INVALID
  • raise an exception, if this was enabled with the feenableexcept(FE_INVALID) glibc extension

I could not find if Java exposes that functionality however.

Here is a minimal runnable C example: What is difference between quiet NaN and signaling NaN?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985