Java For Loop (With Easy Explanation + Real Examples)
β What is a For Loop?
In Java, the for
loop is a control structure used to repeat a block of code a certain number of times. It is best used when the number of iterations is known beforehand. It combines initialization, condition-checking, and increment/decrement in one line, making the loop concise and powerful.
π§ Syntax of the For Loop
Explanation:
-
Initialization: Runs once at the beginning. Usually used to declare and initialize a loop control variable.
-
Condition: Checked before each iteration. If true, the loop continues.
-
Update: Executed after every iteration. Usually used to update the loop control variable.
π― Example 1: Print Numbers from 1 to 5
Output:
π― Example 2: Print Even Numbers from 2 to 10
Output:
π Infinite Loop Using For
You can also create an infinite loop by omitting all three parts:
β οΈ This will run forever unless you use a break
statement or stop the program manually.
π‘ Using Multiple Variables in a For Loop
You can declare and update multiple variables in a for
loop:
Output:
β When to Use a For Loop
-
You know how many times the loop should run.
-
You want compact loop control with initialization, condition, and update in one place.
-
Youβre iterating over arrays or performing counters.