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 = 1 sets the starting value of i to 1.
  • i <= 5 is the condition that keeps the loop running while i is less than or equal to 5.
  • i++ increases the value of i by 1 in each loop.

Each time the loop runs, it prints the current value of i.