In Java, a for loop is a control flow statement used to execute a block of code repeatedly for a specified number of iterations. It is commonly used when the number of iterations is known beforehand.
Syntax:
java
for (initialization; condition; update) {
// Code to be executed
}Components:
1. Initialization: Sets the starting point of the loop, typically declaring and initializing a loop variable.
2. Condition: Evaluates before each iteration. If true, the loop executes; if false, the loop terminates.
3. Update: Modifies the loop variable after each iteration.
Example:
java
for (int i = 0; i < 5; i++) {
System.out.println(“Iteration: ” + i);
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The for loop is efficient and versatile, suitable for tasks like traversing arrays, performing calculations, and more.