Friends! Here is an example:

public class Test { public static void main(String[] args) { int i; int sum = 0; for (i = 1; i <= 5; sum += i++) { System.out.println("Сумма " + sum); } } } 

I went through debugging. I don’t understand why it is output from 0, and not 1, if sum + = i ++ is there, it should be 1? This is what is displayed.

 Сумма 0 Сумма 1 Сумма 3 Сумма 6 Сумма 10 

Please tell me thanks in advance!

1 answer 1

Consider the first iteration:

Initially, i ( i = 1 ) is initialized, then a check will occur ( i <= 5 ), then the value will be output in println , then the expression will execute sum = sum + i++; . Those. first sum displayed, but only then sum = sum + i++; .

Sorry for the picture, painted as I could:

enter image description here

Let us analyze how the expression in the header is executed. sum = 0, i = 1 . After sum = sum + i ( sum = 0 + 1 ), ++ executes and i becomes 2. In more detail, how the increment works in Java (enSO).

  • I do not understand why sum + = i ++ is 4? How is this the first time so skipped? - Petrovchenko Ivan
  • @ PetrovIvan not, this is the order of actions. First 1), then 2) ... 4), then again 1), etc. - Anton Sorokin
  • And why sum + = i ++ not 2? - Petrovchenko Ivan
  • For the first time I see such a design to be honest - Petrovchenko Ivan
  • Anton, are you here? :) - Petrovchenko Ivan