for 

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:

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:

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.

While using a for statement, or any iteration statement for that matter, make sure the exit condition will be reached (unless you deliberately create an infinite loop). That is the main concern around which the iteration statement is built.