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

来源:互联网 发布:淘宝企业店铺缺点 编辑:程序博客网 时间:2024/06/05 14:31

题目
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 stub        short a = 3;        a -=1.6;        System.out.println(a); // prints 1        byte b = 10;        b *= 5.7;        System.out.println(b); // prints 57        byte b1 = 100;        b1 /= 2.5;        System.out.println(b1); // prints 40        char 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的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

0 0
原创粉丝点击