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

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

    The problem here involves type casting.

    When you add int and long,

    1. The int object is casted to long & both are added and you get long object.
    2. but long object cannot be implicitly casted to int. So, you have to do that explicitly.

    But += is coded in such a way that it does type casting. i=(int)(i+m)

    0 讨论(0)
  • 2020-11-21 05:39

    Very good question. The Java Language specification confirms your suggestion.

    For example, the following code is correct:

    short x = 3;
    x += 4.6;
    

    and results in x having the value 7 because it is equivalent to:

    short x = 3;
    x = (short)(x + 4.6);
    
    0 讨论(0)
  • 2020-11-21 05:40

    Yes,

    basically when we write

    i += l; 
    

    the compiler converts this to

    i = (int)(i + l);
    

    I just checked the .class file code.

    Really a good thing to know

    0 讨论(0)
  • 2020-11-21 05:42

    In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:

     byte -> short -> int -> long -> float -> double. 

    The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
    Type - Conversion

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题