Adding int to short
本问题已经有最佳答案,请猛点这里访问。
我的一个同事问我这个问题,我有点困惑。
1 2  | int i = 123456; short x = 12;  | 
声明
1  | x += i;  | 
不过汇编得很好
1  | x = x + i;  | 
不
Java在这里做什么?
1 2 3  | int i = 123456; short x = 12; x += i;  | 
实际上是
1 2 3  | int i = 123456; short x = 12; x = (short)(x + i);  | 
而
A compound assignment expression of the form
E1 op= E2 is equivalent toE1 = (T)((E1) op (E2)) , whereT is the type ofE1 , except thatE1 is evaluated only once.- JLS §15.26.2
数字被视为
1  | x = x + (short)1;  | 
…应该工作。
整型(int、short、char和byte)的
您可以通过以下代码看到:
1 2 3 4 5  | //char x = 0; //short x = 0; //byte x = 0; int x = 0; x = x + x;  | 
它不会编译,除非