我有以下代码:

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。++部分影响求值之后的值,而不是语句之后的值。所以x = x++可以有效地转换成

int y = x; // evaluation
x = x + 1; // increment part
x = y; // assignment

其他回答

 x = x++; (increment is overriden by = )

因为上面的表述x永远不会达到3;

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

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

这是因为x的值根本没有增加。

x = x++;

等于

int temp = x;
x++;
x = temp;

解释:

让我们看看这个操作的字节代码。考虑一个示例类:

class test {
    public static void main(String[] args) {
        int i=0;
        i=i++;
    }
}

现在运行类反汇编程序,我们得到:

$ javap -c test
Compiled from "test.java"
class test extends java.lang.Object{
test();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_0
   1:    istore_1
   2:    iload_1
   3:    iinc    1, 1
   6:    istore_1
   7:    return
}

现在Java虚拟机是基于堆栈的,这意味着对于每个操作,数据将被推入堆栈,从堆栈中,数据将弹出来执行操作。还有另一种数据结构,通常是存储局部变量的数组。局部变量的id是数组的索引。

让我们看看main()方法中的助记符:

iconst_0: The constant value 0 is pushed on to the stack. istore_1: The top element of the stack is popped out and stored in the local variable with index 1 which is x. iload_1 : The value at the location 1 that is the value of x which is 0, is pushed into the stack. iinc 1, 1 : The value at the memory location 1 is incremented by 1. So x now becomes 1. istore_1 : The value at the top of the stack is stored to the memory location1. That is 0 is assigned to x overwriting its incremented value.

因此,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。

答案很简单。它和求值的顺序有关。x++返回值X,然后递增X。

因此,表达式x++的值为0。所以在循环中每次都赋值x=0。当然x++会增加这个值,但这发生在赋值之前。