"+=" operator and int long usage

This question already has an answer here:

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

  • When you do += that's a compound statement and Compiler internally casts it. Where as in first case the compiler straight way shouted at you since it is a direct statement :)

    The line

    b += Long.MAX_VALUE;
    

    Compiler version of it equivalent of

    b += (int)Long.MAX_VALUE;
    

    of course there will be lossy conversion from conversion of long to int.

    http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2

    A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.


    Actually the compiler is smarter than you think. At compile time itself, it will replace the actual value of the expression b+=Long.MAX_VALUE by -1 . So, Long.MAX_VALUE is converted to an int and assigned to the int field at compile time itself)

    Byte code :

    public static void main(java.lang.String[]);
        descriptor: ([Ljava/lang/String;)V
        flags: ACC_PUBLIC, ACC_STATIC
        Code:
          stack=1, locals=2, args_size=1
             0: iconst_0
             1: istore_1
             2: iinc          1, -1 // Here
             5: return
          LineNumberTable:
            line 4: 0
            line 5: 2
            line 6: 5
          LocalVariableTable:
            Start  Length  Slot  Name   Signature
                0       6     0  args   [Ljava/lang/String;
                2       4     1     b   I
    
    链接地址: http://www.djcxy.com/p/12788.html

    上一篇: Java类型混淆

    下一篇: “+ =”运算符和int长的用法