double d=1/0.0;
System.out.println(d);
It prints Infinity
, but if we will write double d=1/0;
and print it we'll get this exception: Exception
in thread "main" java.lang.ArithmeticException: / by zero
at D.main(D.java:3)
Why does Java know in one case that diving by zero is infinity but for the int 0 it is not defined?
In both cases d is double and in both cases the result is infinity.
Floating point data types have a special value reserved to represent infinity, integer values do not.
In your code 1/0
is an integer division that, of course, fails. However, 1/0.0
is a floating point division and so results in Infinity
.