问题描述
如果我有一个字节变量:byte b = 0;
If I have a byte variable: byte b = 0;
为什么以下有效:
b++;
b += 1; // compiles
...但这不是吗?
b = b + 1; // compile error
编译器是否首先理解为byte
,然后理解为int
?
Does compiler understand first as byte
and second as int
?
我知道转换,但我想提请您注意 b++、b += 1 和 b = b + 1
I know casting but I want to draw your attention to the b++, b += 1 and b = b + 1
我认为它们是平等的,为什么编译器会区分它们?
I think they are equal so why compiler differs them ? what is the difference between
b += 1 and b = b + 1 ?
推荐答案
因为 b += 1
等价于 b = (byte)(b + 1)
, 而 b + 1
的类型被提升为 int
(JLS §5.6.2 二进制数字提升),因此如果没有显式转换,其结果不能分配给 byte
.
Because b += 1
is an equivalent to b = (byte)(b + 1)
, whereas type of b + 1
is promoted to int
(JLS §5.6.2 Binary Numeric Promotion) and therefore its result cannot be assigned to byte
without explicit conversion.
E1 op= E2 形式的复合赋值表达式等价于 E1 = (T)((E1) op (E2)),其中 T 是 E1 的类型,只是 E1 只计算一次.
这篇关于为什么 byte += 1 编译但 byte = byte + 1 不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!