-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?

2
  • Example 3 has nothing to do with example 2, since there is no x=x++; code inside. It refers only to example 1, so the result is correct, isn't it? Commented Apr 20, 2015 at 11:58
  • 1
    when x==9 the condition is still valid so x is incremented again, that is why it prints out 10 Commented Apr 20, 2015 at 11:58

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Additional note: Remember that the Do statement is executed before the while condition is evaluated.
@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.
I know (since it's <=) but I wanted to state this anyway. Therfor it's a note on your answer ;).
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.