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
.
Best Answer
Let's focus on the unusual-looking line first:
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:Now let's analyze the processing:
First iteration:
val
andi
are0
.i
is pre-incremented to1
, and that's the result of++i
. The unary+
does nothing, and1
is assigned toval
. Then the iteration statementval++
occurs and nowval
is2
.i
is still1
, so thefor
loop condition is met and a second iteration occurs.Second iteration:
i
is pre-incremented again, to2
. The unary+
does nothing andval
is assigned2
. The iteration statementval++
occurs again and it's now3
. Buti
is now2
, and it's not less than2
, so thefor
loop terminates, andval
--3
- is printed.