for Loop

In this lesson, the concept and implementation of for loops and nested for loops in Java is explained.

for loop: syntax

The for loop is a loop that lets a programmer control exactly how many times a loop will iterate.

The syntax is as follows:

Press + to interact
for (expression for initialization ; expression for testing ; expression for updating) {
//body
}

Here is an example of how the for loop works:

Press + to interact
class Loops {
public static void main(String args[]) {
for (int i = 0; i < 10; ++i) {
// for loop iterates 10 times
System.out.println("value of i = " + i);
}
}
}

Take a look at the illustration below to understand the code above more clearly.

The for loop code above and the while below are more or less equivalent.

Press + to interact
class Loops {
public static void main(String args[]) {
int i = 0;
while (i < 10) // while loop runs till i is less then 10 just like in for loop
{
System.out.println("value of i = " + i); //prints value of i
i++;
}
}
}

What does the for loop do?

...