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

后端 未结 16 2415
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:34

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

相关标签:
16条回答
  • 2020-11-22 03:22

    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
    
    0 讨论(0)
  • 2020-11-22 03:22

    There is a huge difference.

    As most of the answers have already pointed out the theory, I would like to point out an easy example:

    int x = 1;
    //would print 1 as first statement will x = x and then x will increase
    int x = x++;
    System.out.println(x);
    

    Now let's see ++x:

    int x = 1;
    //would print 2 as first statement will increment x and then x will be stored
    int x = ++x;
    System.out.println(x);
    
    0 讨论(0)
  • 2020-11-22 03:25

    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;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 03:27

    When considering what the computer actually does...

    ++x: load x from memory, increment, use, store back to memory.

    x++: load x from memory, use, increment, store back to memory.

    Consider: a = 0 x = f(a++) y = f(++a)

    where function f(p) returns p + 1

    x will be 1 (or 2)

    y will be 2 (or 1)

    And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

    Generally, just use x = x + 1. It's way simpler.

    0 讨论(0)
  • 2020-11-22 03:28

    Yes,

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

    will print 6 and

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

    will print 5.

    0 讨论(0)
  • 2020-11-22 03:28

    With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.

    If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.

    0 讨论(0)
提交回复
热议问题