Why does the following code execute six times? Please help me to understand how this works, as I’ve tried to get it into my head without success.
I thought it would first execute the code once, then increase count to 1, execute it a second time, increase count to 2, execute it a third time, increase count to 3, execute it a fourth time, increase count to 4, execute it a fifth time, increase count to 5, and then stop. Which means it will have executed the loop five times (for the first time, then for when count is 1, 2, 3, 4).
int count = 0;
do {
System.out.println("Welcome to Java!");
} while (count++ < 5);
Have you tried running this code?
output:
This should help you understand what is happening. Has others have said your confusion is most likely in how the post increment operator works.
To help you understand pre and post increment operators lets run another code sample
output:
Summarizing: with post increment the expression is evaluated before the variable is incremented, with pre increment the expression is evaluated after the variable is incremented.