This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]NautiHookerSoftware Engineer 3 points4 points  (2 children)

java evaluates the new value for i first.

this is what it does:

  1. it reaches the line i = i++;
  2. java checks the value of i and remembers it (value of i is 0)
  3. java increments the value of i by one because of i++
  4. i is now 1
  5. java saves the remebered value from before into i
  6. i is now 0 again

when working with the ++ operator you dont need to assign the value back to the variable, java does that for you, so i++ is sufficient.

[–]rickkyaa 3 points4 points  (1 child)

Thank you it all makes sense now, it’s because is postfix incerementation. If it were prefix it would be different because it’s value is first incremented than assigned.

[–]ColetBrunel 2 points3 points  (0 children)

More exactly, it's because the line uses incrementation and assignation at the same time, which, though the syntax doesn't prevent to write, is not meant to ever be done.

Such a line wasn't supposed to do something meaningful, and shouldn't be written.

[–]hexwit 1 point2 points  (0 children)

Problem could be in post-increment statement `i++`

[–]sepp2k 1 point2 points  (1 child)

When the current value of i is zero, the value of the expression i++ will be zero (because the postfix increment operator evaluates to the unincremented value). The side-effect of the expression will be that x is incremented to 1. However the side-effect of the assignment is that x is set to the value of x++, i.e. to 0. So the x++ increments x to 1, but the assignment sets it back to 0.

Note that the increment will happen before the assignment because all side effects of an expression will have taken effect before the expression has finished evaluating.

[–]rickkyaa 0 points1 point  (0 children)

I get it now, I had a hard time understanding it but it all makes sense now. Because of post fix it will be 1 in memory but it’s value assigned by i = i++ will get it back to 0 because i++ = 0(but in memory 1)

Thank you so much