0

I wanted to test if infinity is equal to infinity in Java:

Double.POSITIVE_INFINITY == Double.POSITIVE_INFINITY

I was surprised by the result when it turned out to be true. My question is how can two infinite values be equal?

Prashant
  • 4,775
  • 3
  • 28
  • 47

1 Answers1

7

Because Double.POSITIVE_INFINITY represents a specific number, so comparing it to itself using == should return true.

This behaviour is specified explicitly in JLS Sec 15.21.1:

Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

  • ...

  • Otherwise, two distinct floating-point values are considered unequal by the equality operators.

    In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243