0

Question about challenge question

Why????? Why does this code result in 1 and not 2?!? https://code.sololearn.com/cD79UrxjbAjB/?ref=app

14th Jun 2017, 1:50 PM
Danny K
Danny K - avatar
5 Answers
+ 12
Being more clear, At the run-time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no increment occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion and/or subjected to boxing conversion to the type of the variable before it is stored.  **The value of the postfix increment expression is the value of the variable before the new value is stored.**
14th Jun 2017, 5:02 PM
Dev
Dev - avatar
+ 11
This prints out "1" because it takes x, stores a copy, adds 1 and returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. It would have given the output as "2" if you've just incremented "x" like x = ++x; This is also known as prefixing, adding to the number before using it in the operation.
14th Jun 2017, 4:18 PM
Dev
Dev - avatar
+ 2
Your actual code output 2 ^^ class MyClass { public static void main(String[ ] args) { int x = 1; x = x; x++; System.out.println(x); } } It will output 1, if you modify it like that: class MyClass { public static void main(String[ ] args) { int x = 1; x = x; System.out.println(x++); } } ... but will also input 2 if you write: System.out.println(++x); Because the difference between ++x and x++ is the time where the value is used/modified... - with preincrementation (++x), the value is incremented, and then used; - with postincrementation (x++), the value is used, and then incremented
14th Jun 2017, 6:01 PM
visph
visph - avatar
+ 1
I still don't get it because it says x = x (find and dandy), and THEN increments it to 2. Why wouldn't it print the latest, final version of x after the increment?
14th Jun 2017, 4:27 PM
Danny K
Danny K - avatar
0
Thanks everyone, I know it's a terrible real-world example, and we should avoid using syntax that seems ambiguous or confusing, but sometimes these challenge questions are quite nasty.
14th Jun 2017, 6:06 PM
Danny K
Danny K - avatar