在Java中,x++和++x有什么区别?

140
在Java中,++x和x++有什么区别吗?
18个回答

338

++x被称为前增量,而x++被称为后增量。

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6

76

是的

++x会先将x的值加1,然后返回x的值
x++返回x的值,然后再将其加1

例子:

x=0;
a=++x;
b=x++;

代码运行后,a和b的值都将变为1,但x的值将为2。


21

这些被称为后缀和前缀运算符。两者都会将变量加1,但语句结果有所不同。

int x = 0;
int y = 0;
y = ++x;            // result: x=1, y=1

int x = 0;
int y = 0;
y = x++;            // result: x=1, y=0

应该是 后缀 吧? - user4157653

12

在Java中,x++和++x有所不同

++x是前缀形式: 它会先对变量的表达式进行递增,然后再使用该表达式的新值。

例如,如果在代码中使用:

int x = 3;

int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4

System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'

x++是后缀形式:该变量的值首先在表达式中使用,然后在操作后递增。

例如,如果在代码中使用:

int x = 3;

int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4

System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4' 

希望这很清楚。运行并使用上述代码进行操作应有助于您的理解。


11
是的,
int x=5;
System.out.println(++x);

将打印6

int x=5;
System.out.println(x++);

将打印5


1
这个“答案”只是告诉你一个测试用例的输出,我认为输出并不算是答案。相反,通常代码执行的(意外)结果会引导我们提出问题。因此我投了反对票。 - Alberto de Paola

9
我从其中一个最近的副本跳转到了这里,虽然这个问题已经得到了解答,但我还是忍不住反编译了代码并添加了“另一个答案” :-)
为了准确(可能有点学究),
int y = 2;
y = y++;

被编译成:

int y = 2;
int tmp = y;
y = y+1;
y = tmp;

如果您编译这个Y.java类:

public class Y {
    public static void main(String []args) {
        int y = 2;
        y = y++;
    }
}

如果你执行javap -c Y,你会得到以下的jvm代码(我已经在Java虚拟机规范的帮助下对主方法进行了注释):

public class Y extends java.lang.Object{
public Y();
  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_2 // Push int constant `2` onto the operand stack. 

   1:   istore_1 // Pop the value on top of the operand stack (`2`) and set the
                 // value of the local variable at index `1` (`y`) to this value.

   2:   iload_1  // Push the value (`2`) of the local variable at index `1` (`y`)
                 // onto the operand stack

   3:   iinc  1, 1 // Sign-extend the constant value `1` to an int, and increment
                   // by this amount the local variable at index `1` (`y`)

   6:   istore_1 // Pop the value on top of the operand stack (`2`) and set the
                 // value of the local variable at index `1` (`y`) to this value.
   7:   return

}

因此,我们最终拥有:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp

9

在考虑计算机实际执行的操作时...

++x: 从内存中加载x,增加值,使用,再存回内存。

x++: 从内存中加载x,使用,增加值,再存回内存。

考虑以下代码: a = 0 x = f(a++) y = f(++a)

其中函数f(p)返回p + 1

x将为1(或2)

y将为2(或1)

问题就在这里。编译器的作者是在获取参数后、使用后还是存储后传递参数呢?

通常,只需使用x = x + 1即可。它更简单。


4
是的。
public class IncrementTest extends TestCase {

    public void testPreIncrement() throws Exception {
        int i = 0;
        int j = i++;
        assertEquals(0, j);
        assertEquals(1, i);
    }

    public void testPostIncrement() throws Exception {
        int i = 0;
        int j = ++i;
        assertEquals(1, j);
        assertEquals(1, i);
    }
}

3

如果像其他许多语言一样,您可能希望尝试简单的方法:

i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check

如果上述内容没有按照预期发生,它们可能是等效的。

3
是的,返回的值分别是自增前和自增后的值。
class Foo {
    public static void main(String args[]) {
        int x = 1;
        int a = x++;
        System.out.println("a is now " + a);
        x = 1;
        a = ++x;
        System.out.println("a is now " + a);
    }
}

$ java Foo
a is now 1
a is now 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接