What is the difference between i ++ vs i = i + 1 in an if statement?

For the first code

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

System Outputs: 3 5 7 9

For the second code

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

System Outputs: 2 4 6 8 10

Why are the two outputs different from each other, but the formula is the same?

+4
source share
2 answers

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

In the case, the i = i + 1opposite takes place: first it will be increased, and only then will the calculation be performed.

If you want to have the behavior of the second case with a multiplicity of the first, use ++i: in this case i, it will first be increased to calculation.

, docs Assignment, Arithmetic Unary Operators!

+3

i = i+1 i, .

i++ i, , , .

0

All Articles