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

后端 未结 11 1341
暖寄归人
暖寄归人 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:31

    you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like

    i = i + (int)l;
    

    or

    i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
    

    but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.

提交回复
热议问题