“+=” operator and int long usage
本问题已经有最佳答案,请猛点这里访问。
1 | int a = 1L; |
当然,这不会编译。不兼容的类型:从long到int的可能有损转换
1 2 |
这是编译的!
但为什么允许这样做?
当您执行
线
1 |
它的编译器版本相当于
1 |
当然会有从long到int的有损转换。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html jls-15.26.2
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.
实际上,编译器比你想象的要聪明。在编译时,它将用
字节码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=2, args_size=1 0: iconst_0 1: istore_1 2: iinc 1, -1 // Here 5: return LineNumberTable: line 4: 0 line 5: 2 line 6: 5 LocalVariableTable: Start Length Slot Name Signature 0 6 0 args [Ljava/lang/String; 2 4 1 b I |