java是干什么的,什么是“+ =”运营商用Java做什么?

在Java中,`x += y`并不总是等同于`x = x + y`。当`x`和`y`类型不同时,复合赋值运算符会进行隐式类型转换,而普通加法则需要显式转换。例如,如果`x`是`int`类型,`y`是`double`类型,`x += 1.1`会被编译,但`x = x + 1.1`则不会。这是因为`+=`会自动将结果转换为`x`的类型,而`+`操作需要手动转换第二个操作数。
摘要由CSDN通过智能技术生成

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

x += 0.1;

解决方案

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.

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

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.

Quote from Joshua Bloch's Java Puzzlers:

(...) 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].

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值