Java For Loop
Syntax, Flow & Examples
Java For Loop
The for loop in Java is used to repeat a block of code a certain number of times. It's concise, predictable, and incredibly useful when you know in advance how many times a loop should run.
Syntax of a Java For Loop
for (initialization; condition; update) {
// code block to be executed
}
This syntax has three parts:
- Initialization: Executed once before the loop starts.
- Condition: Checked before each iteration. Loop continues if this is
true. - Update: Executed after each iteration. Usually increments or decrements a variable.
For Loop Basic Example: Print 1 to 5
This example shows how to use a for loop in Java to print numbers from 1 to 5.
Here’s how it works:
int i = 1sets the starting value ofito 1.i <= 5is the condition that keeps the loop running whileiis less than or equal to 5.i++increases the value ofiby 1 in each loop.
Each time the loop runs, it prints the current value of i.