Reputation: 313
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
.
Upvotes: 10
Views: 602
Reputation: 4483
if the operator used was +=
you will be adding to val
the value of i+1
.
in your case you are assigning to val the value of i+1
each time,
on the final iteration i = 2
so val = 3
.
Upvotes: 0
Reputation: 178323
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.
Upvotes: 18
Reputation: 313
Corrected calculation:
val i
0 0 i<2 = true;
0 0 ++i;
0 1 val = +i = 1;
1 1 (end of for loop) val++;
2 1 i<2 = true;
2 1 ++i;
2 2 val = +i = 2;
2 2 (end of for loop) val++;
3 2 i<2 = false;
Output: 3
Upvotes: 0
Reputation: 2630
There is no =+
operator in Java, according to the official documentation. Use +=
instead to get desired effect.
Upvotes: 0