For loops are particularly useful when the number of iterations is known beforehand. Instead of using a while loop, the for loop provides a concise and clear way to iterate through a block of code a specific number of times.
Syntax
for (initialization; condition; increment) { // code block to be executed }
Initialization: This is executed once before the loop starts.
Condition: Defines the condition for executing the code block.
Increment: Executes after the code block has been executed every time.
Example
The following example prints numbers from 0 to 4:
for (int counter = 0; counter < 5; counter++) { System.out.println(counter); }
Example Explained:
- Initialization: Sets a variable (
int counter = 0
) before the loop starts. - Condition: Determines the condition for the loop to run (
counter
must be less than 5). If true, the loop continues; if false, the loop ends. - Increment: Increases the variable (
counter++
) after each iteration of the loop.
Another Example
This example prints even numbers between 0 and 10:
for (int index = 0; index <= 10; index = index + 2) { System.out.println(index); }