Java 原始型铸造
我最近一直在使用Java的字节原语,我遇到了一个愚蠢的问题:Java 原始型铸造,java,Java,我最近一直在使用Java的字节原语,我遇到了一个愚蠢的问题: byte a = 10; byte b = 9; byte c = 8; b += b*c; // how come this statement is correct without any explicit type casting b = b*c; // while this statement is incorrect; it requires explicit cast, of course b = b+(b*
byte a = 10;
byte b = 9;
byte c = 8;
b += b*c; // how come this statement is correct without any explicit type casting
b = b*c; // while this statement is incorrect; it requires explicit cast, of course
b = b+(b*c); // this is wrong too.
所以我的问题是,
+=
是否指定了除了add和assign之外的任何赋值,或者这是Java中的一个错误(我几乎可以肯定不是)?所有复合赋值运算符不仅执行该操作,而且还自动将其结果转换为左侧变量的类型
因此,你的+=不仅添加变量并分配结果-它还将结果强制转换为正确的类型。因为
b+=b*c
相当于b+=(字节)((b)+(b*c))
从Java语言规范的以下内容:
形式为E1 op=E2的复合赋值表达式等价于E1=(T)((E1)op(E2)),其中T是E1的类型,但E1仅计算一次