I was experiencing Java primitive types ranges, and I came up with a small confusion, here is some line of code that illustrates clearly what is it about:
System.out.println((byte) (Math.pow(2, 7))+1); //the maximum value + 1 overflows to the minimum value
System.out.println((short) (Math.pow(2, 15)-1)); //same for shorts
System.out.println((int) Math.pow(2, 31));
System.out.println((int) (Math.pow(2, 31)+1)); //returns the maximum value of the int range
System.out.println((int) (Math.pow(2, 31)+100)); //returns the maximum value of the int range
Math.pow(2, 7)
is 128.0
, which is more than can fit in a byte
. When you cast, it becomes -128
. Add 1 and it becomes -127
.
The same behavior applies to your short
example.
As for the int
example, you should apply the (int)
cast before you do your addition +
. In your current case, the +
happens with a double
and an int
. Numeric promotion happens on the int
to convert it to a double
. Then it's just a matter of precision.
System.out.println(Math.pow(2,31) + 1);
prints
2.147483649E9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With