什么是“+ =”运营商用Java做什么?

编程入门 行业动态 更新时间:2024-10-28 22:23:37
本文介绍了什么是“+ =”运营商用Java做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

x += 0.1;

推荐答案

编程的常识是 x + = y 是 x = x + y 的等效简写表示法。只要 x 和 y 属于同一类型(例如,两者都是 int s),您可以认为这两个语句是等价的。

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.

如果 x 且 y 属于不同类型,由于语言规则,这两个语句的行为不同。例如,让我们有 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 ]。

更多推荐

什么是“+ =”运营商用Java做什么?

本文发布于:2023-11-23 23:37:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:做什么   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!