Search code examples
javaprimitive-types

Why java int type has valid value in range -2,147,483,648 to 2,147,483,647?


I'm wondering why java int type (32 bit signed) has valid value in range -2,147,483,648 to 2,147,483,647 but not in (-2,147,483,648 to 2,147,483,648)?


Solution

  • The primary representation of numbers in modern computers is some form of binary representation. It consists of a fixed number of bits that take the values 0 or 1. In Java, an int is specified to use a binary representation with 32 bits.

    A 32 bit binary representation can have 2^32 states. (This is a mathematical fact. It can be proven from first principles.)

    Consider the mathematical integers from -2^31 to +2^31:

    • There are 2^31 numbers in the range 1 to 2^31 (inclusive)

    • There are 2^31 numbers in the range -1 down to -(2^31) (inclusive)

    • The value zero is not in either of the above ranges.

    So counting the numbers from -2^31 to +2^31, we get a total of 2^31 + 2^31 + 1 values. That is 2^32 + 1 which is more values than can be represented in 2^32 states.

    What you are suggesting is not mathematically possible.