>cannot convert from int to char. a+=b

This question already has an answer here:

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

  • The answer lies in binary numeric promotion. All operand are promoted to the type of the wider operand, and up to at least int . This is described by the JLS, Section 5.6.2:

    2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int .

  • (emphasis mine)

    Therefore a char ( checkSum ) plus a char ( charNum[i] ) is an int .


    It is more simple than you think :).

    If you add two char 's, it creates int . Always.


    And you are not right in few things : The values of cells in array of char is char , not reference, therefore charNum[i] is char and it is only 2 bytes width.

    链接地址: http://www.djcxy.com/p/12792.html

    上一篇: 为什么b = b + 1当b是一个字节时不会编译,但b + = 1编译

    下一篇: >不能从int转换为char。 一个+ = B