首页 > 解决方案 > 为什么 Int 中 MAX_VALUE 的溢出使其为负值,但在字节中保持为正值?

问题描述

public class Hello {
    public static void main(String[] args){
        int myMinIntValue = Integer.MIN_VALUE;
        int myMaxIntValue = Integer.MAX_VALUE;

        System.out.println("The min Value Integer can hold is " + myMinIntValue);
        System.out.println("The Maximum Value Integer can hold is " + myMaxIntValue);
        System.out.println("The BUSTED MAX INT value is "+ (myMaxIntValue+1));
        System.out.println("The BUSTED Min INT value is "+ (myMinIntValue-1));
        System.out.print( "\n");


        byte myMinByteValue = Byte.MIN_VALUE;
        byte myMaxByteValue = Byte.MAX_VALUE;

        System.out.println("The min Value Byte can hold is " + myMinByteValue);
        System.out.println("The Maximum Value Byte can hold is " + myMaxByteValue);
        System.out.println("The BUSTED MAX Byte value is "+ (myMaxByteValue+1));
        System.out.println("The BUSTED Min Byte value is "+ (myMinByteValue-1));
        System.out.print( "\n");

    }
}

退货

The min Value Integer can hold is -2147483648
The Maximum Value Integer can hold is 2147483647
The BUSTED MAX INT value is -2147483648
The BUSTED Min INT value is 2147483647

The min Value Byte can hold is -128
The Maximum Value Byte can hold is 127
The BUSTED MAX Byte value is 128
The BUSTED Min Byte value is -129

The min Value Short can hold is -32768
The Maximum Value Short can hold is 32767
The BUSTED MAX Short value is 32768
The BUSTED Min Short value is -32769

在 Int 的情况下,当我们添加 +1 时,Integer 可以容纳的最大值是 2147483647(因为 OVER 流它变为负数,但是在 Byte 的情况下,如果我们添加 +1,它会一直添加?有人解释为什么会这样?

标签: java

解决方案


当您将两个数字相加时,操作数会进行二进制数字提升

如有必要,首先将操作数拆箱;然后第一个匹配规则适用:

  • 如果一个操作数是双精度数,则另一个操作数加宽为双精度数
  • 如果一个操作数是浮点数,则将另一个加宽为浮点数
  • 如果一个操作数是长整数,则另一个操作数加宽为长整数
  • 否则,两者都扩大到 int。

由于1是一个int(因为它是一个int字面量),将它添加到一个字节意味着最后一条规则适用,因此该字节被扩大为一个int;两个整数相加的结果是一个整数。

因为 128 在 int 范围内,所以不会发生溢出。

请注意,规则不会比 int 更窄,因此即使添加两个字节也会导致 int:

System.out.println(Byte.MAX_VALUE + (byte) 1); // 128

另请注意,如果您使用前/后增量:

byte myMaxByteValue = Byte.MAX_VALUE;
++myMaxByteValue;

那么 的值为maxByte-128。这是因为预增量相当于:

myMaxByteValue = (byte) (myMaxByteValue + 1);

即有一个隐式转换回变量类型。


推荐阅读