So I'm new to programming in Java and I'm just having a hard time understanding why this
for (int i = 0, j=0; i <10; i++) {
System.out.println(j += j++);
}
prints out 0 ten times?
So I'm new to programming in Java and I'm just having a hard time understanding why this
for (int i = 0, j=0; i <10; i++) {
System.out.println(j += j++);
}
prints out 0 ten times?
j += j++
can be thought of as
j = j + j++
Now, we start with j = 0, so j++ increments j and returns its old value of 0 (!), hence we essentially are left with
j = 0 + 0
// ^ ^
// j j++
ten times. The incrementation of j is overriden by the fact that we reassign j to the outcome of the right hand side (0) just after.
Sometimes I find it helpful to look at the bytecode. j += j++ is really:
ILOAD 1 // load j, which is 0
ILOAD 1 // load j, which is 0
IINC 1 1 // j++
IADD // add top two stack elements
ISTORE 1 // store result back in j
Since IINC does not alter the stack in any way, IADD adds the value of j to itself: 0 + 0. This result is stored back into j by ISTORE after j has been incremented by IINC.
In j += j++ you are actually doing
j = j + j++;
so for j=0 you will get
j = 0 + j++
and since j++ will increment j after returning its value you will get
j = 0 + 0;
for now after j++ j will be equal to 1 but, after calculating 0+0 it will return to 0 and that value will be printed.
Are you unsure about the for-loop? int i = 0 declares an int i, and sets it to 0. j = 0 also declares another int j, and sets it to 0. i < 10 states that while i is less than 10, the loop will keep on going. Finally, i++ states that every time the loop is done, i = i + 1, so essentially one will be added to i.
System.out.println(++j);
instead of
System.out.println(j += j++);