Java increment and assignment operator

微笑、不失礼 提交于 2019-11-27 08:41:18

No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x and post-increment x++ compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.

Here is the sequence of events that leads to what you see:

  • x is assigned 10
  • Because of ++ in post-increment position, the current value of x (i.e. 10) is stored for later use
  • New value of 11 is stored into x
  • The temporary value of 10 is stored back into x, writing right over 11 that has been stored there.

Post Increment(n++) : First execute the statement then increase the value by one.

Pre Increment (++n) : First increase the value by one then execute the statement.

Example:

class IncrementTest{
    public static void main(String[] args){

        System.out.println("***Post increment test***");
        int n = 10;
        System.out.println(n);      // output  10
        System.out.println(n++);    // output  10
        System.out.println(n);      // output  11

        System.out.println("***Pre increment test***");
        int m = 10;
        System.out.println(m);      // output  10
        System.out.println(++m);    // output  11
        System.out.println(m);      // output  11
    }
}

Quoting from The Java tutorials - Assignment, Arithmetic, and Unary Operators:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

I also stumbled by the trickiness of post-increment operator while preparing for a Java certification exam. Most, even the experienced, think post-increment (++) operator increments the variable after the execution of the statement, just as @bartektartanus stated above. This thinking is good enough for most real world coding, but breaks down if a post/pre-incremented/decremented variable occurs more than once within a statement. Looks like the so-called interview/knowledge test questions promptly check for this loose assumption. It is worth breaking this up. The accepted answer above is not so helpful for a concise, logical mnemonic.

public class Test {
    static int x = 10;

    public static void main(String[] args) {
        print(x++);
    }

    private static void print(int x) {
        System.out.println(x);
        System.out.println(Test.x);
    }
}

Output
10
11

Per the common assumption, the static variable x would be incremented after completion of the call to the print method. But when checked inside the method, it has already been incremented. So, post- increment, decrement operaters submit the variable value to the method or operator to which they are parameters, and increment/decrement the associated variable immediately before the operator/method gets executed. The pre-increment/decrement operation is somewhat less confusing, but again even this happens per method or operator, not the whole statement.

// The OP
int x = 10;
x = x++; // x = 10. x does get incremented but before the assignment operation

int x = 10;
x = x++ + x; // x = 21. x got incremented immediately after the addition operator grabbed its value.

I have not found a reference in JLS, so this answer is predicated on the speculation that you are not invoking undefined behavior, because this is Java.

x = x++; // Assign the old value of `x` to x, before increment.
x = ++x; // Assign the new value of `x` to x, after increment.

This is the based on the definition of postfix and prefix operators.

When you do this:

x = x++;

It actually is translated to "Assign 'x' to 'x' and then increment 'x' by one".

Whereas in this case:

x = ++x;

It gets translated to "Increment 'x' by one, then assign it to 'x'".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!