JAVA不同数据类型的取值范围与溢出现象
2020-05-06 本文已影响0人
仙姑本姑
基本类型 | 大小 | 最小取值 | 最大取值 | 包装类型 |
---|---|---|---|---|
Int | 32bit | -2^31(2147483648) | 2^31-1(2147483647) | Integer |
short | 16bit | -2^15(-32768) | 2^15-1(32768) | Short |
long | 64bit | -2^63 | 2^63-1 | Long |
float | 32bit | IEEE754 | IEEE754 | Float |
double | 64bit | IEEE754 | IEEE754 | Double |
char | 16bit | Unicode o | Unicode 2^16-1 | Charater |
byte | 8bit | 2^7(-128) | 2^7-1(127) | Byte |
boolean | - | - | - | Boolean |
溢出问题
在JDK中,整形类型是有范围的,最大值为Integer.MAX_VALUE,即2147483647,最小值为Integer.MIN_VALUE -2147483648。
对整形最大值加1,2147483648(越界了),那么此时值为多少呢?结果是-2147483648,即是Integer.MIN_VALUE。
类似的,对Integer.MIN_VALUE取反或者取绝对值呢?仍为Integer.MIN_VALUE,因为值为-2147483648,绝对值2147483648超过Integer.MAX_VALUE 2147483647。
所以就有以下结果
Integer.MAX_VALUE + 1 = Integer.MIN_VALUE
Math.abs(Integer.MIN_VALUE) = Integer.MIN_VALUE (绝对值)
Long,short,byte的结论是相同的。
IEEE754详解:https://www.jianshu.com/p/e5d72d764f2f