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

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

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

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

    In Java there is a difference between x++ and ++x

    ++x is a prefix form: It increments the variables expression then uses the new value in the expression.

    For example if used in code:

    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++ is a postfix form: The variables value is first used in the expression and then it is incremented after the operation.

    For example if used in code:

    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' 
    

    Hope this is clear. Running and playing with the above code should help your understanding.

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

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

    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.

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

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

    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);  
    }
    
    0 讨论(0)
提交回复
热议问题