So there is a program that displays the following:

13 15 x = 6

But it’s not quite clear why x = 6, and not 7 (as it seemed to me to go), and why the value of y displays after 13 not 14, but 15 at once

public class Output { public static void main(String[] args) { Output o = new Output(); o.go(); } void go() { int y = 7; for (int x = 1; x < 8; x++) { y++; if (x > 4) { System.out.print(++y + " "); } if (y > 14) { System.out.println(" x = " + x); break; } } } } 

PS Explain how the program behaves after x reaches a value of 5

  • because you double increment y in a loop - etki
  • Well, this is understandable, but the logic is not entirely clear. Why x = 6, not 7? Why is y equal to first 13, and then right there 15, where 14 disappears - Alex Sh.
  • 2
    @ Alexey Shavkunov, use the debugger and see with your own eyes how the variables change when you go through each line. It will be much clearer, and faster than waiting for you to chew everything here. - PinkTux

1 answer 1

Why 13 and then immediately 15?

When the condition x > 4 is satisfied for the first time ( x = 5 ), at this moment the postfix increment y++ gives 12, and the prefix increment in System.out.print(++y + " "); gives y = 13 . The second iteration, when x = 6 , again, two increments are triggered and at the output we get y = 15 .

Why x = 6, not 7?

When the condition y > 14 is fulfilled, at this moment x = 6 , in the body of the condition this is printed and break ends the for loop, so x does not reach the value 7.