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.
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.
Copyright © 2021 Jogjafile Inc.
Effectively, the expression
i=i++ + i++;is equal toi=i++ + i;. Why? The latteri++result value is never used and is not propagated. The result of the postfix additioni++is used as long as the valueiis added later in the expression and the result takes the effect. However, after the latteri++the result value ofiis 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 theivariable: