Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
Luke Vo Avatar asked Aug 31 '26 23:08

Luke Vo


1 Answers

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.

like image 167
Jeremy Avatar answered Sep 03 '26 12:09

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!