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

后端 未结 16 2440
-上瘾入骨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.

提交回复
热议问题