“+="是什么意思运算符在Java中做什么? [英] What does the "+=" operator do in Java?

查看:61
本文介绍了“+="是什么意思运算符在Java中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您帮我理解以下代码的含义:

Can you please help me understand what the following code means:

x += 0.1;

推荐答案

编程的常识"是 x += yx = x + 的等效简写符号y.只要 xy 的类型相同(例如,都是 ints),你可以认为这两个语句是等价的.

The "common knowledge" of programming is that x += y is an equivalent shorthand notation of x = x + y. As long as x and y are of the same type (for example, both are ints), you may consider the two statements equivalent.

然而,在 Java 中,x += y 通常与 x = x + y 相同.

However, in Java, x += y is not identical to x = x + y in general.

如果xy 是不同的类型,由于语言的规则,这两个语句的行为是不同的.例如,让我们有 x == 0 (int) 和 y == 1.1 (double):

If x and y are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0 (int) and y == 1.1 (double):

    int x = 0;
    x += 1.1;    // just fine; hidden cast, x == 1 after assignment
    x = x + 1.1; // won't compile! 'cannot convert from double to int'

+= 执行隐式转换,而对于 +,您需要显式转换第二个操作数,否则会出现编译器错误.

+= performs an implicit cast, whereas for + you need to explicitly cast the second operand, otherwise you'd get a compiler error.

引自 Joshua Bloch 的 Java Puzzlers:

Quote from Joshua Bloch's Java Puzzlers:

(...) 复合赋值表达式自动转换结果他们对变量类型执行的计算左手边.如果结果的类型与变量,演员表没有效果.但是,如果结果比变量宽,复合赋值运算符执行静默缩小原语转换 [JLS 5.1.3].

(...) compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion [JLS 5.1.3].

这篇关于“+="是什么意思运算符在Java中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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