gpt4 book ai didi

java - 为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要将 long 转换为 int?

转载 作者:行者123 更新时间:2023-12-01 18:42:47 24 4
gpt4 key购买 nike

直到今天,我认为例如:

i += j;

只是一个快捷方式:

i = i + j;

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

int i = 5;
long j = 8;

然后 i = i + j; 将无法编译,但 i += j; 可以正常编译。

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

最佳答案

与往常一样,JLS 给出了这些问题的答案。在这种情况下§15.26.2 Compound Assignment Operators 。摘录:

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;

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

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

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

关于java - 为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要将 long 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59889340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com