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等大牛。衷心但愿有更多的好论坛出现~ 同时求推荐一些好的技术论坛
相关文章
相关标签/搜索