Java的+ =, - =,* =,/ =复合赋值运算符 [英] Java's +=, -=, *=, /= compound assignment operators

查看:141
本文介绍了Java的+ =, - =,* =,/ =复合赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到今天为止,我还是想:例如:

Until today I thought that for example:

i += j;

只是一个捷径:

i = i + j;

但是,如果我们尝试这个:

But what if we try this:

int i = 5;
long j = 8;

然后 i = i + j; 不编译,但 i + = j; 将编译正确。

Then i = i + j; will not compile but i += j; will compile fine.

这是否意味着事实上 i + = j; 是类似这样东西的快捷方式
i =(i的类型)(i + j)

Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?

推荐答案

与这些问题一样,JLS保留了答案。在这种情况下,§15.26.2复合分配操作符< a>。提取:

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:


以下形式的复合赋值表达式 E1  op =  E2 等效于 E1  = (T)((E1) (E2)),其中 T E1 的类型,除了 E1 只计算一次。

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

§15.26.2


[...]

[...] the following code is correct:

short x = 3;
x += 4.6;

,结果x的值为7,因为它等价于:

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);


换句话说,你的假设是正确的。

In other words, your assumption is correct.

这篇关于Java的+ =, - =,* =,/ =复合赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆