Java Puzzlers筆記--puzzle 9: Tweedledum +=的問題

 Provide declarations for the variables x and i such that this is a legal statement:
 x += i;
but this is not:
 x = x + i;

Solution:
 short x = 0;
 int i = 123456;
 x += i; // Contains a hidden cast!
 x = x + i; //Won't compile - "possible loss of precision"

TID:
 compound assignment expressions automatically cast the result of the computation the

perform to the type of the variable on their left-hand side.
 do not use compound assignment operators on variables of type byte, short, or char.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章