Java typecasting confusion

This question already has an answer here:

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

  • The first works and the second doesn't because the *= += -= etc add an automatic cast .

    If, for example, you were to change your second example to;

    int k=10;
    double kk = 10.10;
    k*= kk;
    

    It should work. Alternatively you could just add an explicit cast like so rst = (int)(k*kk);


    The arithmetic promotion in Java happens when you apply an arithmetic operation on two variables with different data-types. In this case the compiler will convert the data type of one operand in the binary arithmetic operation to the type of the other operand.

    In your case, for multiplying an int and a double, the int is promoted to double, and the result is double. So, it can't be stored into an int.

    See more at: http://www.codemiles.com/java/arithmetic-promotion-t3487.html#sthash.sdHtt7pG.dpuf


    The result of the multiplication of an integer ( int ) and a floating point in java will always result in a floating point ( double ). You are assigning this result to the integer rst which requires casting.

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

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

    下一篇: Java类型混淆