为什么字节的最大值加一,但没有溢出

Dor*_*ris 2 java byte overflow

class Overflowtest {

  public static void main(String[] args) {

    byte maxValue= Byte.MAX_VALUE;
    System.out.println("maxValue of byte is "+maxValue);
    System.out.println("add 1 to maxValue of byte is "+maxValue+(byte)2);

  }
}
Run Code Online (Sandbox Code Playgroud)

为什么我尝试时没有发生溢出maxValue+(byte)2?但如果我这样做(byte)(maxValue+2),溢出就发生了.

Tia*_*ssi 5

在您的示例中,您将127添加到字符串,然后将2添加到字符串.

但是当你这样做时:

System.out.println(maxValue+(byte)2);
Run Code Online (Sandbox Code Playgroud)

二进制运算返回一个整数.