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

2018-12-31 07:43发布

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

16条回答
孤独寂梦人
2楼-- · 2018-12-31 08:33

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.

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
查看更多
几人难应
3楼-- · 2018-12-31 08:33

Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression. Take an example:

public static void main(String args[])
{
    int i , j , k = 0;
    j = k++; // Value of j is 0
    i = ++j; // Value of i becomes 1
    k = i++; // Value of k is 1
    System.out.println(k);  
}
查看更多
只若初见
4楼-- · 2018-12-31 08:34

yes

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

example:

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

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

查看更多
梦醉为红颜
5楼-- · 2018-12-31 08:35

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.

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;
  }
}
查看更多
登录 后发表回答