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

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

    Sometimes, such a question can be asked at an interview.

    For example, when you write:

    int a = 2;
    long b = 3;
    a = a + b;
    

    there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.

    So to avoid it, you must write your code like this:

    int a = 2;
    long b = 3;
    a += b;// No compilation error or any exception due to the auto typecasting
    

提交回复
热议问题