Consider this code:
long val = 0;
for(int i = 0; i < 2; val++)
val =+ ++i;
System.out.println(val);
Why is val = 3 in the end?
I would have calculated like this:
val i
0 0 i < 2 = true;
0 0 ++i;
0 1 val =+ 1;
1 1 (end of for loop) val++;
2 1 i < 2 = true;
2 1 ++i;
2 2 val =+ 2;
4 2 (end of for loop) val++;
5 2 i < 2 = false;
Output: 5
But it's 3. I don't understand why the increment val =+ ++i is not done the second time when i = 1 and getting pre-incremented to i = 2.
Let's focus on the unusual-looking line first:
val =+ ++i;
The operators here are = (assignment), + (unary plus), and ++ (pre-increment). There is no =+ operator. Java interprets it as two operators: = and +. It's clearer with appropriate whitespace added:
val = + ++i;
Now let's analyze the processing:
First iteration: val and i are 0. i is pre-incremented to 1, and that's the result of ++i. The unary + does nothing, and 1 is assigned to val. Then the iteration statement val++ occurs and now val is 2. i is still 1, so the for loop condition is met and a second iteration occurs.
Second iteration: i is pre-incremented again, to 2. The unary + does nothing and val is assigned 2. The iteration statement val++ occurs again and it's now 3. But i is now 2, and it's not less than 2, so the for loop terminates, and val -- 3- is printed.
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