Reputation: 3167
In for(int i=0; i < 5; i++)
loop isn't i
incremented by i++
already before the printf reads it? If so it should return i=1
right? What's the concept here that returns 0
at first.
public class Application {
public static void main(String[] args) {
for(int i=0; i < 5; i++) {
System.out.printf("The value of i is: %d\n", i);
}
}
}
Upvotes: 1
Views: 1807
Reputation: 1
In the for loop first the loop run checking only if the i < 5.Since it is true the its will give access into the loop where still i remains zero(0) and execute the statements inside the loop and then increment i by one (i++).Where then the incremented i will be taken into the consideration of the condition.
Upvotes: 0
Reputation: 11671
The behavior is the same as
for(int i=0; i < 5; ) {
System.out.printf("The value of i is: %d\n", i);
//whatever
//at the very end; just before exiting the loop
i = i + 1;
// exit the loop
}
Upvotes: 0
Reputation: 49656
14.14.1. The basic for Statement
BasicForStatement: for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed. Then there is a choice:
If execution of the Statement completes normally, then the following two steps are performed in sequence:
First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated.
Second, another for iteration step is performed.
In your example, it means i++
will be executed after the System.out.printf
line.
Upvotes: 2
Reputation: 1025
No, the loop incrementation is computed at the end of the loop body.
Upvotes: 0