原帖链接:http://www.iteye.com/topic/1117960
简单说一下问题,LZ要求解释下面的Java代码,x为什么最后是1。
Integer x = 1;
x = x++;
System.out.println(x);
不管这么说,我觉得这个问题还不错,这个帖子最后还是被隐藏了,事实上这个帖子并没有“标题党”。 不得不说ITeye上的风气是越来越浮躁了,为什么就不肯静下心来好好讨论呢,至少给出理由给出证据,而不是随手投个隐藏。
OK,进入正题。
这里表面上是关于x++的讨论,但实际上也涉及到Java中自动拆装箱的问题。
首先看《The Java Language Specification, Third Edition》中15.14.2 Postfix Increment Operator ++的描述:
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.
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.
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.
这儿明确说明了:(1)拆箱(unboxing conversion);(2)将变量的值加一的和存储回这个变量;(3)这个表达式的值为将新值存储回变量之前变量的值;(4)装箱(boxing conversion)。
用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的时候,感叹优快云的没落,没想到现在轮到ITeye了。不过还好,ITeye上还有RednaxelaFX,wenshao,icyfenix等大牛。衷心希望有更多的好论坛出现~ 同时求推荐一些好的技术论坛
本文深入探讨了Java中x++操作的运行机制,详细解释了自动拆装箱、变量值加一存储回变量的过程及表达式值的确定。

168

被折叠的 条评论
为什么被折叠?



