1

Seen source code of Double.java and some constants are like

/**
 * Constant for the Not-a-Number (NaN) value of the {@code double} type.
 */
public static final double NaN = 0.0 / 0.0;

/**
 * Constant for the positive infinity value of the {@code double} type.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

/**
 * Constant for the negative infinity value of the {@code double} type.
 */
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

but I wonder why it is not throwing ArithmeticException(divide by zero)?

and I have tried

 public static final int VALUE = 0/0;

now it's throwing Exception but when I say

 public static final double VALUE = 0d/0d;

it is not throwing exception...

What's the magic of Double and why it is not throwing Exception?

Gopal Gopi
  • 11,101
  • 1
  • 30
  • 43

3 Answers3

11

The "magic" is that Java floating point representations are based on the IEE 754 floating point standard. This has a special value (NaN) that denotes the "indefinite value" that you get when zero is divided by zero. (There are also values that represent positive and negative infinity; e.g. 1.0 / 0.0 gives INF - positive infinity.)

This is covered in the Java Language Specification; see sections §4.2.3 which discusses the representations and §4.2.4 which discusses how arithmetic works.


Note that the same "magic" applies to float, double, Float and Double.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Because something that is undefined in the number system cannot be obviously represented. "Undefined" is not a number (NaN) and double/float have NaN to indicate that.

IEEE 754

"arithmetic formats: sets of binary and decimal floating-point data, which consist of finite numbers (including signed zeros and subnormal numbers), infinities, and special "not a number" values (NaNs)"

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
  • Ermm ... NaN does not represent infinity. INF represents infinity. Zero divided by zero is "indefinite". – Stephen C Dec 17 '13 at 11:33
1

Doubles in Java (and some but not all other languages) support values that are NaN (Not a number).

Operations like a division by 0 will give you a double which is NaN.

Any operation involving a NaN will also result in a NaN.

Wikipedia has a whole page on the subject of NaN:

http://en.wikipedia.org/wiki/NaN

Tim B
  • 40,716
  • 16
  • 83
  • 128