-3

I'm trying to understand post incrementation at the hand of these 3 examples. But I have difficulties trying to understand the last one.

1.

int x = 0;
x++;
System.out.println(x); //prints out 1 

2.

int x = 0;
x = x++;
System.out.println(x); //prints out 0. 

x in itself contains 1, but not the left side reference variable pointing to x seeing it's post-incrementation. So the original value is returned.

3.

int x = 0;
do {
    x++;
} while (x <= 9);
System.out.println(x); // prints out 10

But according to my reasoning based on the first 2 examples it should print out 9. x in itself first contains 1, then 2, 3, 4, 5, 6, 7, 8, 9. Could someone please explain the output for the last example?

Daniel Stanley
  • 1,050
  • 6
  • 15
Helenesh
  • 3,999
  • 2
  • 21
  • 36

2 Answers2

3

As long as x <= 9, the while loop won't be terminated, so x must by 10 after the loop.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Additional note: Remember that the Do statement is executed before the while condition is evaluated. – GregD Apr 20 '15 at 12:00
  • 1
    @GregD In this case it makes no difference. Even if the loop was `while (x <= 9) {x++;}`, you'd still get 10 after the loop. – Eran Apr 20 '15 at 12:02
  • I know (since it's <=) but I wanted to state this anyway. Therfor it's a note on your answer ;). – GregD Apr 20 '15 at 12:05
1

The loop continues until x > 9. The first value for this condition to be true is 10.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139