java中的x++和++x有区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1094872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:38:31  来源:igfitidea点击:

Is there a difference between x++ and ++x in java?

javasyntaxoperatorsincrement

提问by erickreutz

Is there a difference between ++x and x++ in java?

java中的++x和x++有区别吗?

采纳答案by Emil H

++x is called preincrement while x++ is called postincrement.

++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

回答by Johannes Weiss

Yes,

是的,

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

will print 6and

将打印6

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

will print 5.

将打印5

回答by Victor

yes

是的

++x increments the value of x and then returns x
x++ returns the value of x and then increments

++x 递增 x 的值然后返回 x
x++ 返回 x 的值然后递增

example:

例子:

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

after the code is run both a and b will be 1 but x will be 2.

代码运行后,a 和 b 都是 1,但 x 是 2。

回答by nojevive

Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.

是的,使用++X,表达式中将使用X+1。使用 X++,X 将在表达式中使用,并且 X 只会在表达式被计算后增加。

So if X = 9, using ++X, the value 10 will be used, else, the value 9.

因此,如果 X = 9,使用 ++X,将使用值 10,否则使用值 9。

回答by flq

If it's like many other languages you may want to have a simple try:

如果它像许多其他语言一样,您可能想要一个简单的尝试:

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

If the above doesn't happen like that, they may be equivalent

如果上面没有那样发生,它们可能是等价的

回答by Carl Manaster

Yes.

是的。

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);
    }
}

回答by Lars Haugseth

Yes, the value returned is the value after and before the incrementation, respectively.

是的,返回的值分别是增量前后的值。

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

回答by Pablojim

These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.

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

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

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

回答by Alberto

I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)

我从最近的一个dup来到这里,虽然这个问题已经得到了回答,但我还是忍不住反编译了代码并添加了“另一个答案”:-)

To be accurate (and probably, a bit pedantic),

准确地说(可能有点迂腐),

int y = 2;
y = y++;

is compiled into:

编译成:

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

If you javacthis Y.javaclass:

如果你javac这个Y.java班级:

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

and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):

并且javap -c Y,您将获得以下 jvm 代码(我允许我在Java 虚拟机规范的帮助下评论 main 方法):

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

}

Thus, we finally have:

因此,我们终于有:

0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp

回答by kasaquan

OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.

好的,我来到这里是因为我最近在检查经典堆栈实现时遇到了同样的问题。提醒一下,这是在 Stack 的基于数组的实现中使用的,它比链表快一点。

Code below, check the push and pop func.

下面的代码,检查推送和弹出功能。

public class FixedCapacityStackOfStrings
{
  private String[] s;
  private int N=0;

  public FixedCapacityStackOfStrings(int capacity)
  { s = new String[capacity];}

  public boolean isEmpty()
  { return N == 0;}

  public void push(String item)
  { s[N++] = item; }

  public String pop()
  { 
    String item = s[--N];
    s[N] = null;
    return item;
  }
}