Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

后端 未结 11 1313
暖寄归人
暖寄归人 2020-11-21 05:06

Until today, I thought that for example:

i += j;

Was just a shortcut for:

i = i + j;

But if we try this:<

11条回答
  •  情书的邮戳
    2020-11-21 05:46

    The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do

    int a=5;
    long b=10;
    a+=b;
    System.out.println(a);
    

    What you're really doing is:

    int a=5;
    long b=10;
    a=a+(int)b;
    System.out.println(a);
    

提交回复
热议问题