duk*_*vin 8 java variable-assignment compound-operator
方法是:
x -= y;
Run Code Online (Sandbox Code Playgroud)
相当于:
x = x - y;
Run Code Online (Sandbox Code Playgroud)
pol*_*nts 38
不,它们与你表达它们的方式不相同.
short x = 0, y = 0;
x -= y; // This compiles fine!
x = x - y; // This doesn't compile!!!
// "Type mismatch: cannot convert from int to short"
Run Code Online (Sandbox Code Playgroud)
第三行的问题是-执行操作数的所谓"数字提升"(JLS 5.6)short,并产生一个int值,不能简单地将其赋值给short没有强制转换的值.复合赋值运算符包含隐藏的强制转换
确切的等价在JLS 15.26.2化合物分配操作符中列出:
形式E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,除了E1仅被评估一次.
所以澄清一些细微之处:
int x = 5; x *= 2 + 1; // x == 15, not 11int i = 0; i += 3.14159; // this compiles fine!arr[i++] += 5; // this only increments i onceJava也有*=,/=,%=,+=,-=,<<=,>>=,>>>=,&=,^=和|=.最后3个也是为布尔值定义的(JLS 15.22.2布尔逻辑运算符).