为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要强制转换? [英] Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

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

问题描述

直到今天,我认为例如:

Until today, I thought that for example:

i += j;

只是一个快捷方式:

i = i + j;

但是如果我们尝试这样做:

But 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复合赋值运算符.摘录:

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) op (E2)),其中TE1的类型,除了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天全站免登陆