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

时间:2012-10-27 12:03:30

标签: java int variable-assignment scjp ocpjp

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或者更小的表达式的结果总是为int,即使两个字节的总和适合一个字节。

当我们添加两个适合字节的最终字节时,为什么会这样? 没有编译器错误。

3 个答案:

答案 0 :(得分:29)

From the JLS 5.2 Assignment Conversion

  

此外,如果表达式是byte,short,char或int 类型的常量表达式(第15.28节):     - 如果类型为,则可以使用缩小的基元转换      变量是byte,short或char,以及常量的值      表达式可以在变量的类型中表示。

简而言之,表达式的值(在编译时已知,因为它是一个常量表达式)可以在byte的变量类型中表示。

考虑你的表达

 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

答案 1 :(得分:9)

byte z = x + y;  // x and y are declared final

此处,由于xy被声明为final所以RHS上的表达式的值在编译时是已知的,其固定为{{1}并且不能改变。因此,您不需要明确地对其进行类型转换

(1 + 2 = 3)

然而,在这种情况下,byte c = a + b; // a and b are not declared final a的值未声明为最终值。因此,表达式的值在编译时是未知的,而是在运行时计算。所以,你需要做一个明确的演员。


但是,即使在第一个代码中,如果b的值超出范围a + b,它也将无法编译。

-128 to 127

答案 2 :(得分:0)

只要我们在两个变量a和b之间执行任何算术运算,结果始终为

max(int, type of a, type of b)

byte a=10;
byte b=20;
byte c=a+b(C.E )

说明:如上所述 max(int,a的类型,b的类型)

max(int,byte,byte)

结果的类型为:int,找到的是int,但以字节为单位

所以我们需要将类型转换成字节

    byte a=10;
    byte b=20;
    byte c=(byte) (a+b);