For Loop in Java
A for loop is a control flow statement used to repeatedly execute a block of code
for a certain number of times. It is typically used when the number of iterations is known in
advance.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
Explanation of Components:
- Initialization: Initializes the loop counter variable. Executed only once at
the beginning of the loop.
- Condition: The loop continues to execute as long as this condition evaluates to
true.
- Update: This updates the loop control variable after each iteration (e.g.,
increment or decrement).
Working of for loop:
- The loop starts by initializing the variable.
- Then the condition is checked.
- If the condition is true, the loop body is executed.
- After execution, the update expression runs.
- The condition is checked again and the process repeats until the condition becomes false.
Use Cases:
- Iterating over arrays or collections
- Running a fixed number of repetitions
- Printing patterns or sequences
- Batch processing of data
Advantages of for loop:
- Compact and easy to understand
- Initialization, condition, and update are all in one line
- Ideal for counter-controlled repetition