6

Output of the below code confusing me. Why NaN sometimes and Infinity other times ?

public static void main (String[] args) {

    double a = 0.0;
    double b = 1.0;
    int c = 0; 
    System.out.println(a/0.0);
    System.out.println(a/0);
    System.out.println(b/0.0);
    System.out.println(b/0);
    System.out.println(c/0.0);
    System.out.println(c/0);
}

Outputs is:

NaN
NaN
Infinity
Infinity
NaN
Exception in thread "main" java.lang.ArithmeticException: / by zero

What is the deciding factor here ?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    The Java Language Specification. https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2 – JB Nizet Aug 11 '18 at 15:16
  • 2
    That's most likely standardized as per IEEE-754: https://stackoverflow.com/a/12954429/14955 – Thilo Aug 11 '18 at 15:17
  • 1
    I've seen that you haven't accepted any useful answer. **If one of the asnwers is helpful, accept it by clicking tick below number on the left side** – Soner from The Ottoman Empire Aug 11 '18 at 16:21
  • Note that `a/0`, `b/0` is going to be identical to `a/0.0` and `b/0.0` respectively: the two operands undergo *binary numeric promotion*, meaning practically that the int denominator is widened to a double. – Andy Turner Aug 11 '18 at 18:25

1 Answers1

5

This is because of The IEEE Standard for Floating-Point Arithmetic (IEEE 754) which is a technical standard for floating-point computation established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE).


The purpose:

The IEEE floating-point standard,.. specifies that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number). There are two zeroes: +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing.


The Rule:

In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0.


Source

Yahya
  • 13,349
  • 6
  • 30
  • 42