If it takes all 32 bits to store from -2^31 to 2^31, how can it store + and - Infinite? Does it use mo开发者_JAVA百科re 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.
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.
If it takes all 32
bytebits to store from -2^31 to 2^31...
There you're talking about Integer
s.
...how can it store + and - Infinite?
There you're talking about Float
and Double
, which are different data types. Float
is a 32-bit IEEE 754 number, and Double
is a 64-bit IEEE 754 number. IEEE 754 floating-point numbers have special values set aside for positive and negative infinity.
There is no special "infinity" value in Java's Integer
class, you can store the full range of values.
精彩评论