当前位置: 代码迷 >> 综合 >> 003:Java's +=, -=, *=, /= compound assignment operators
  详细解决方案

003:Java's +=, -=, *=, /= compound assignment operators

热度:53   发布时间:2023-12-13 06:54:31.0

题目
Until today I thought that for example:

i += j;

is just a shortcut for:

i = i + j;

But what if we try this:

int i = 5;
long j = 8;

Then i = i + j; will not compile but i += j; will compile fine.

Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?

解答
复合赋值操作符

short x = 3; x += 4.6;

等价于

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

最后x = 7

对其他三种情况同理


public class stackoverFlow {public static void main(String[] args) {// TODO Auto-generated method stubshort a = 3;a -=1.6;System.out.println(a); // prints 1byte b = 10;b *= 5.7;System.out.println(b); // prints 57byte b1 = 100;b1 /= 2.5;System.out.println(b1); // prints 40char ch = '0';ch *= 1.1;System.out.println(ch); // prints '4'char ch1 = 'A';ch1 *= 1.5;System.out.println(ch1); // prints 'a'}}

本专题来源stackoverflow 标签是java的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

  相关解决方案