Java Puzzler - casting a double to int

后端 未结 1 1462
难免孤独
难免孤独 2021-01-18 04:16
int anInt = 1;
double aDouble = 2.5;

anInt = anInt + aDouble; // Error - need to cast double to int

anInt += aDouble; // This is ok. Why?

anInt = aDouble; // This         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 04:50

    Three of the four cases properly report an error. Compound assignment is the only exception from the rule. Java Language Specification, part 15.26.2, explains why:

    15.26.2 Compound Assignment Operators

    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.

    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);
    

    As you can see, the error is avoided by implicit insertion of a cast.

    0 讨论(0)
提交回复
热议问题