How does a for loop check its conditions in Java?
for-loop, java
Solution
The initializer expression happens once. Then the condition is checked, then the body of the loop happens, then the increment expression happens (your `print` statement), and then we start over.
The official tutorial is pretty clear if you read through it.
The Java Language Specification entry for the `for` statement might also be interesting if you want complete details.
Problem
My question has to do with the order in which java checks the conditions of a for loop when there is a print statement in the "conditions" of the loop. It seems like an unpractical thing to do (I haven't ever seen it used in any practical way), though my lack of understanding of what is printed has me thinking that I may not fully understand how a for loop functions. The following question showed up on a recent exam: What will the following method print with an input of n = 5? ``` public static void mystery(int n) { for (int i = -1; i < n; System.out.print(i + " ")) { i++; } } ``` The correct answer is: 0 1 2 3 4 5 To me, it seems that the loop ought to print -1, then increment i by 1, print 0 ..... until i = 4. Then it would print 4, increment i by 1, and break out of the loop at the loop's condition i < n. Why is the correct answer what it is and why is my logic flawed?