Search code examples
javamathmemoryinfinite

How does Java store +-Infinite in memory?


If it takes all 32 bits to store from -2^31 to 2^31, how can it store + and - Infinite? Does it use more memory? Is it good and safe to store those values?

UPDATE: Thanks to the answers, I know that only floating point data types can store Inf value, Integers can't.


Solution

  • Java, along with most other programming languages, follows the IEEE 754 specification for floating point numbers. The range of the possible values is slightly reduced to allow for the infinities as well as NaN (Not a Number). These are safe to store; they're even available as constants, for example Double.POSITIVE_INFINITY.

    If it takes all 32 byte to store from -2^31 to 2^31

    I think you mean 32 bits, to store all of the possible integer values in this range. Java's Integer type works as you describe, and has no way to store infinities or other special values.