9

For the 1st code,

int i = 1;
while (i < 10)
    if ((i++) % 2 == 0)
        System.out.println(i);

The system outputs: 3 5 7 9

For the 2nd code,

int i = 1;
while (i < 10)
    if ((i=i+1) % 2 == 0)
        System.out.println(i);

The system outputs: 2 4 6 8 10

Why are the two outputs different but the formula is the same?

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
bwuxiaop
  • 85
  • 1
  • 1
  • 4
  • Oh gosh, this was one of my first assignments in college .. – dbf May 16 '15 at 21:40
  • Not quite the same, `i++` and `++i` is really all about postfix and prefix incrementation. Although `i=i+1` is a prefix equivalent of `++i`, it's not the same. The argument for only being equivalent and not the same is simple, with `i=i+5` i can add 5 every iteration, with `++i` i cannot. – dbf May 16 '15 at 21:47
  • @byako The reason for me for not being a dupe is because the plain question you linked goes _whats the difference between post- en prefix incrementation_. This questions supplies an example which gives the OP an _unexpected_ result, which clearly means to me that the shorthand prefix `++i` is not being identified as `i=i+1`. Where again, the only code-able explanation for prefixed incrementation `++i`, is again `i=i+1`, to make it visually understandable. – dbf May 16 '15 at 22:06
  • @dbf fair enough. I've removed my previous comment. – byako May 16 '15 at 22:19
  • 1
    it goes without saying that any code where the difference between j++ and ++j matters is automatically bad code (using j=j+1 inside an equality moves beyond bad). Once you add in the multiline braceless ifs both become examples of "what not to do" – Richard Tingle May 16 '15 at 22:28

2 Answers2

9

If you use i++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

For i = i + 1, the opposite is the case: It will first be incremented and only then the calculation will take place.

If you want to have the behavior of the second case with the brevity of the first, use ++i: In this case, i will first be incremented before calculating.

For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

i = i+1 will increment the value of i, and then return the incremented value.

i++ will increment the value of i, but return the original value that i held before being incremented.

Llogari Casas
  • 942
  • 1
  • 13
  • 35