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?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With