The format of the basic for statement looks as follows:
for(ListInit; Boolean Expression; ListUpdate) block or statement
But, we will start with the most popular, much simpler, version and get back to the full version in the For with multiple initializers and expressions section later. The simpler basic for statement format looks like this:
for(DeclInitExpr; Boolean Expression; IncrDecrExpr) block or statement
This definition consists of the following components:
- DeclInitExpr is a declaration and initialization expression, like x = 1, that is evaluated only once at the very beginning of the for statement's execution
- Boolean Expression is a Boolean expression, like x < 10, that is evaluated at the beginning of each iteration – every time before executing the block or statement; if the result is false, the for statement terminates
- IncrDecrExpr is an increment or a decrement unary expression, like ++x, --x, x++, x-, that is evaluated at the end of each iteration – after the block or statement is executed
Notice that we talk about expressions, not statements, although with added semicolons, they look like statements. The reason for that is that a semicolon serves as the separator between the expressions in the for statement. Let's look at an example:
for (int i=0; i < 3; i++){
System.out.print(i + " "); //prints: 0 1 2
}
In this code:
- int i=0 is the declaration and initialization expression, evaluated only once at the very beginning
- i < 3 is the Boolean expression, evaluated at the beginning of each iteration – before executing the block or statement; if the result is false ( i >= 3, in this case), the for statement execution terminates
- i++ is the increment expression, evaluated after the block or statement is executed
And, as in the case of a while statement, the braces {} are not needed when only one statement has to be executed, but it is a good style to have them, so the code is consistent and easier to read.
None of the expressions in a for statement are required:
int k = 0;
for (;;){
System.out.print(k++ + " "); //prints: 0 1 2
if(k > 2) break;
}
But using expressions in the statement declaration is more convenient and conventional, thus easier to understand. And here are other examples:
for (int i=0; i < 3;){
System.out.print(i++ + " "); //prints: 0 1 2
}
for (int i=2; i > 0; i--){
System.out.print(i + " "); //prints: 2 1
}
Notice how in the last example, the decrement operator is used to walk down the initial i value.