为什么我不能添加两个字节,并得到一个int,我可以添加两个最后的字节获得一个字节?

public class Java{ public static void main(String[] args){ final byte x = 1; final byte y = 2; byte z = x + y;//ok System.out.println(z); byte a = 1; byte b = 2; byte c = a + b; //Compiler error System.out.println(c); } } 

如果涉及int-sized或更小的任何expression式的结果总是int,即使两个字节的总和适合一个字节。

为什么当我们添加两个字节的最终字节? 没有编译器错误。

从JLS 5.2分配转换

此外, 如果expression式是byte,short,char或inttypes的常量expression式(第15.28节) : – 如果variables的types为byte,short或char,则可以使用缩小的基元转换,常量expression式在variables的types中是可表示的。

简而言之,expression式的值(在编译时已知,因为它是一个常量expression式)在字节variables的types中是可表示的。

考虑你的表情

  final byte x = 1; final byte y = 2; byte z = x + y;//This is constant expression and value is known at compile time 

所以总结符合字节它不会引起编译错误。

现在如果你这样做

 final byte x = 100; final byte y = 100; byte z = x + y;// Compilation error it no longer fits in byte 
 byte z = x + y; // x and y are declared final 

在这里,由于xy被声明为final因此RHS上的expression式的值在编译时已知,固定在(1 + 2 = 3)且不能改变。 所以,你不需要明确地说明它

 byte c = a + b; // a and b are not declared final 

而在这种情况下, ab值并不是最终的。 因此,expression式的值在编译时是不知道的,而是在运行时进行评估。 所以,你需要做一个明确的演员。


然而,即使在第一个代码中,如果a + b的值超出了-128 to 127的范围,它也将无法编译。

 final byte b = 121; final byte a = 120; byte x = a + b; // This won't compile, as `241` is outside the range of `byte` final byte b1 = 12; final byte a1 = 12; byte x1 = a1 + b1; // Will Compile. byte can accommodate `24`