1

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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • It's a loop that iterates 10 times. The value of `j += j++` is zero each time. – jahroy Sep 12 '13 at 01:32
  • Go through on this http://stackoverflow.com/a/5413593/2291134. – gjman2 Sep 12 '13 at 01:48
  • You've gotten some explanations of why it does what it does. But, please: **don't do this** in real code. Don't put two things that change the same variable in the same expression. In some languages, the behavior of this kind of code may change from one compiler to another. In Java, the behavior may be better defined, but it will still be torture for anyone who tries to understand the code. – ajb Sep 12 '13 at 01:48

4 Answers4

5
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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

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.

-1
System.out.println(++j);

instead of

System.out.println(j += j++); 
newuser
  • 8,338
  • 2
  • 25
  • 33
  • 3
    This doesn't answer the question, it tells how to achieve the output you _assume_ the OP wants... – jahroy Sep 12 '13 at 01:35