javajava-17jshellpostfix-operator

Why does jshell show this number?


I am learning java and this logic makes me feel confused.

Isn't here i=20(+1)+20(+1)?

Why 41 instead of 42?

jshell> int i = 20
i ==> 20
jshell> i=i++ + i++
i ==> 41

See this code run at Ideone.com.


Solution

  • Effectively, the expression i=i++ + i++; is equal to i=i++ + i;. Why? The latter i++ result value is never used and is not propagated. The result of the postfix addition i++ is used as long as the value i is added later in the expression and the result takes the effect. However, after the latter i++ the result value of i is not used.

    If you want to achieve the result of 42, you need to perform the postfix assignment (i++) after the whole result is assigned back to the i variable:

    int i = 20;
    i = i++ + i;
    i++;
    System.out.println(i);