整型(byte、short、int、long)取值范围
byte 1字节,取值范围:-128 ~ 127 (-2^7 ~ 2^7-1)
short 2字节,取值范围:-32768 ~ 32767 (-2^15 ~ 2^15-1)
int 4字节,取值范围:-2147483648 ~ 2147483647 (-2^31 ~ 2^31-1)
long 8字节,取值范围:-9223372036854775808 ~ 9223372036854775807 (-2^63 ~ 2^63-1)
Integer的最小值和最大值
Integer 中 MIN_VALUE、MAX_VALUE 两个常量
测试代码
@Test
public void int_min_max() {
System.out.println(Integer.MIN_VALUE + " <=> "+Integer.toBinaryString(Integer.MIN_VALUE));
System.out.println(-BigDecimal.valueOf(2).pow(31).longValue());
System.out.println(Integer.MAX_VALUE + " <=> "+Integer.toBinaryString(Integer.MAX_VALUE));
System.out.println(BigDecimal.valueOf(2).pow(31).longValue() - 1);
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);
}
打印结果
-2147483648 <=> 10000000000000000000000000000000
-2147483648
2147483647 <=> 1111111111111111111111111111111
2147483647
true
测试发现下面表达式为 true
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
或
Integer.MIN_VALUE - 1 == Integer.MAX_VALUE
一个死循环的例子
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
//todo
}
只有当i比int最大值大的时候才能结束循环,而i就是是int类型,永远不会比int最大值大,且
当 i=Integer.MAX_VALUE, 再加一变成了 Integer.MIN_VALUE
int类型能表示的最小负数
int类型最小的负数的二进制补码是1000 0000 0000 0000 0000 0000 0000 0000
这里实际上是使用补码-0来表示-2147483648的(对-2147483648的补码表示[1000 0000 0000 0000 0000 0000 0000 0000] 补,算出来的原码是[0000 0000 0000 0000 0000 0000 0000 0000]原,这是不正确的)在考虑32位有符号整数时,-2147483648只有补码[1000 0000 0000 0000 0000 0000 0000 0000],没有原码,只是硬性规定补码[1000 0000 0000 0000 0000 0000 0000 0000]表示-2147483648。