我有以下代码:

public class Tests {
    public static void main(String[] args) throws Exception {
        int x = 0;
        while(x<3) {
            x = x++;
            System.out.println(x);
        }
    }
}

我们知道他应该只写x++或x=x+1,但在x=x+ +时,它应该先把x归为自己,然后再加1。为什么x的值是0 ?

- - -更新

下面是字节码:

public class Tests extends java.lang.Object{
public Tests();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[])   throws java.lang.Exception;
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   iconst_3
   4:   if_icmpge   22
   7:   iload_1
   8:   iinc    1, 1
   11:  istore_1
   12:  getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   15:  iload_1
   16:  invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   19:  goto    2
   22:  return

}

我会仔细阅读说明,试着理解……


当前回答

这是因为在这种情况下它永远不会增加。x++会先使用它的值,然后再进行递增,在这种情况下,它会像这样:

x = 0;

但如果你用++x;这将会增加。

其他回答

没有一个答案是完全正确的,所以是这样的:

当你写int x = x++时,你不是把x赋值为它自己的新值,你是把x赋值为x++表达式的返回值。也就是x的原始值,正如Colin Cochrane的答案所暗示的那样。

为了好玩,测试下面的代码:

public class Autoincrement {
        public static void main(String[] args) {
                int x = 0;
                System.out.println(x++);
                System.out.println(x);
        }
}

结果将是

0
1

表达式的返回值是x的初始值,即0。但是稍后,当读取x的值时,我们会收到更新后的值,即1。

你不需要机器代码来理解发生了什么。

根据定义:

赋值操作符求右边表达式的值,并将其存储在临时变量中。 1.1. x的当前值被复制到这个临时变量中 1.2. X现在是递增的。 然后将临时变量复制到表达式的左侧,也就是x !这就是为什么原来的x值又被复制到自身。

这很简单。

我想是因为在java++中有比=(赋值)更高的优先级…不是吗? 看看http://www.cs.uwf.edu/~eelsheik/cop2253/resources/op_precedence.html…

同理,如果x=x+1。+的优先级高于=(赋值)

你有效地得到了以下行为。

获取x的值(它是0)作为右边的“结果” 增加x的值(x现在是1) 将右边的结果(保存为0)分配给x (x现在是0)

其思想是,后增量操作符(x++)在返回变量的值后对该变量进行增量,以便在使用该变量的方程中使用。

编辑:由于评论的原因,稍微增加了一点。像下面这样考虑。

x = 1;        // x == 1
x = x++ * 5;
              // First, the right hand side of the equation is evaluated.
  ==>  x = 1 * 5;    
              // x == 2 at this point, as it "gave" the equation its value of 1
              // and then gets incremented by 1 to 2.
  ==>  x = 5;
              // And then that RightHandSide value is assigned to 
              // the LeftHandSide variable, leaving x with the value of 5.

该值保持在0,因为x++的值为0。在这种情况下,x的值是否增加并不重要,赋值x=0被执行。这将覆盖x的临时增量值(在“非常短的时间”为1)。