ITeye上「10我的,8我的不會解釋這個問題」的帖子

原帖連接:http://www.iteye.com/topic/1117960html

簡單說一下問題,LZ要求解釋下面的Java代碼,x爲何最後是1。java

Integer x = 1;
x = x++;
System.out.println(x);

無論這麼說,我以爲這個問題還不錯,這個帖子最後仍是被隱藏了,事實上這個帖子並無「標題黨」。 不得不說ITeye上的風氣是愈來愈浮躁了,爲何就不願靜下心來好好討論呢,至少給出理由給出證據,而不是隨手投個隱藏。express

OK,進入正題。app

這裏表面上是關於x++的討論,但實際上也涉及到Java中自動拆裝箱的問題。post

首先看《The Java Language Specification, Third Edition》15.14.2 Postfix Increment Operator ++的描述:lua

A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.spa

At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.code

Note that the binary numeric promotion mentioned above may include unboxing conversion (§5.1.8) and value set conversion (§5.1.13). If necessary, value set conversion is applied to the sum prior to its being stored in the variable.orm

這兒明確說明了:(1)拆箱(unboxing conversion);(2)將變量的值加一的和存儲回這個變量;(3)這個表達式的值爲將新值存儲回變量以前變量的值;(4)裝箱(boxing conversion)。htm

用Java代碼表示x=x++即:

int int_x = x.intValue();
int exprValue = int_x;
int_x = int_x + 1;
Integer integer_exprValue = Integer.valueOf(exprValue);
x = integer_exprValue;

事實上從class文件中也能夠看出:

0 iconst_1
 1 invokestatic #2 <java/lang/Integer.valueOf>
 4 astore_1
 5 aload_1
 6 astore_2
 7 aload_1
 8 invokevirtual #3 <java/lang/Integer.intValue>
11 iconst_1
12 iadd
13 invokestatic #2 <java/lang/Integer.valueOf>
16 dup
17 astore_1
18 astore_3
19 aload_2
20 astore_1
21 getstatic #4 <java/lang/System.out>
24 aload_1
25 invokevirtual #5 <java/io/PrintStream.println>
28 return
PS:當初發現JavaEye的時候,感嘆CSDN的沒落,沒想到如今輪到ITeye了。不過還好,ITeye上還有RednaxelaFX,wenshao,icyfenix等大牛。衷心但願有更多的好論壇出現~ 同時求推薦一些好的技術論壇
相關文章
相關標籤/搜索