0

When I wrote this code in Java

int i, j;
for(i = 0 ,  j=0 ; i < 10; i++)
{
    j += j++;
    System.out.println(j);
}

the output always equals 0, while the same code in c++ outputs 1023. Why does it give me zero in Java?

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50

1 Answers1

1

Your code j += j++ can be written as :

j = j + j++

You have initialised j as 0. Now while evaluating the expression j++ means post increment. In other words, the value stored in j would be incremented by 1 after this step has been executed. So for evaluation of this step, the j has the value of 0 stored in it. So, you are basically evaluating 0 + 0 and storing the result in the variable j. So, the variable j gets assigned a new value 0 after completion of this step.

Now coming back to the point of j++ which is suppose to happen after the execution of this step does not happen because the value that was supposed to be incremented has been lost. So the increment does not take place.

After your edit you found that instead of using j++ if you used ++j you are getting the desired result. That is because ++j is pre-increment. if you take the evaluation steps, the expression j = j + ++j would evaluate as 0 + 1 in the first loop as j is incremented before execution. So, you get the desired result.

Blip
  • 3,061
  • 5
  • 22
  • 50