java字节一元运算
我们都知道,在Java中,这些操作符:
a++;
++a;
a += 1;
a = a + 1;
做同样的事情,他们只需将1添加到变量“a”中
然而,为什么这些说法不全是真的,背后的原则是什么
byte a = 1;
a++;
++a;
a += 1;
a = a + 1; // This line will result to a compile time error
为什么
你可以在下面搜索框中键入要查询的问题!
我们都知道,在Java中,这些操作符:
a++;
++a;
a += 1;
a = a + 1;
做同样的事情,他们只需将1添加到变量“a”中
然而,为什么这些说法不全是真的,背后的原则是什么
byte a = 1;
a++;
++a;
a += 1;
a = a + 1; // This line will result to a compile time error
为什么
# 1 楼答案
a=a+1
这是由于表达式的类型
a = a + 1;
。LHS被提升为int
,然后执行加法。然后,您尝试将int
值重新分配给byte
而无需强制转换参考JLS 5.6.2
a++; ++a
这里的类型就是变量的类型。同样按照JLS 15.15
a+=1
根据JLS 15.26.2
因此这里
a += 1;
等同于a = (byte)(a+1);
,因为它是隐式完成的# 2 楼答案
每当在两个不同类型的操作数之间执行二进制运算时,其中一个操作数将升级为更高的类型。然后操作的结果就是这种类型
因此,在您的例子中,
byte
类型a
首先被提升为int
,因为1
是int
类型。然后在加法运算之后,结果是类型int
。现在,由于无法将int
分配给byte
,因此需要执行类型转换以删除编译器错误:现在,在复合赋值运算符的情况下,类型转换是为您隐式完成的。表达方式:
在内部转换为:
这在JLS-§15.26.2 Compound Assignment Operator中指定:
前缀增量运算符和后缀增量运算符的情况类似
根据JLS-§15.15 Unary Operators: