Java int += double syntax surprise

This question already has an answer here:

  • Varying behavior for possible loss of precision 2 answers
  • Why does Java perform implicit type conversion from double to integer when using the “plus equals” operator? [duplicate] 2 answers
  • Why don't Java's +=, -=, *=, /= compound assignment operators require casting? 11 answers

  • x += 0.5;
    

    is equivalent to:

    x = (int) (x + 0.5)
    

    In general:

    x += y is equivalent to x = (type of x) (x + y)


    See 15.26.2. Compound Assignment Operators


    x += 0.5; is the same as x = (int) (x + 0.5); .


    这是因为复合赋值操作符会进行隐式转换 (自动转换):所以

    x+=0.5 => x =(int)(x + 0.5) => x = (int)(7.5) => x = 7
    
    链接地址: http://www.djcxy.com/p/12786.html

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

    下一篇: Java int + =双语法惊喜