5
double d=1.0/0.0;

output is Infinity

double d=1/0;

output is ArithmeticException.

What is difference between between these two? What is meaning of Infinity here?

Christian Neverdal
  • 5,655
  • 6
  • 38
  • 93
user3593753
  • 87
  • 1
  • 6

3 Answers3

6

The first case is treated as a division on double and the later as a division on int and hence the ArthimeticException.

Here is what infinity means

http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#POSITIVE_INFINITY

The division of doubles and floats is as per the IEEE 754 standards for floating point match which shouldnt throw an exception.

Kalyan Chavali
  • 1,330
  • 8
  • 24
0

Mathematically, division by zero is undefined, although it can be loosely be regarded as being infinity. (With a little more rigour, it's a number that is greater than x for any value of x.)

An IEEE754 floating point double (used by Java) has a representation of infinity. That is the result of 1.0 / 0.0. In that sense, 1.0 / 0.0 is calculable since it takes place in floating point arithmetic.

An integral type has no representation of infinity, so an exception is thrown. 1 / 0 is computed in integer arithmetic.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

floating point number have a way to code "infinity". So infinity is a valid value for a double variable. Integer variables do not have this option. So an exception is thrown instead.

Matthias
  • 3,458
  • 4
  • 27
  • 46