我有以下代码:

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增加 x之前的值赋给x。

其他回答

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

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

从http://download.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

为了说明这一点,请尝试以下方法:

    int x = 0;
    int y = 0;
    y = x++;
    System.out.println(x);
    System.out.println(y);

它会输出1和0。

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

当你写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。

其他人已经解释得很好了。我只包含了指向相关Java规范部分的链接。

X = x++是一个表达式。Java将遵循求值顺序。 它将首先计算表达式x++,该表达式将增加x并将结果值设置为x的前一个值。 然后它将表达式结果赋值给变量x。最后,x返回到它之前的值。

检查下面的代码,

    int x=0;
    int temp=x++;
    System.out.println("temp = "+temp);
    x = temp;
    System.out.println("x = "+x);

输出将是,

temp = 0
x = 0

后增量是指将值递增,并返回该增量之前的值。这就是temp值为0的原因。那么如果temp = i并且这是在一个循环中(除了第一行代码)。就像问题!!!!一样