Java for loop
The for
loop in Java is a control structure that allows you to execute a block of code repeatedly for a specified number of times. It is particularly useful when the number of iterations is known beforehand.
Syntax of the for
Loop
for (initialization; condition; update) {
// Block of code to be executed
}
- initialization: This step is executed once at the beginning of the loop. It is typically used to declare and initialize a loop control variable.
- condition: Before each iteration, this condition is evaluated. If it evaluates to
true
, the loop body executes. If it evaluates tofalse
, the loop terminates. - update: This step is executed at the end of each iteration. It typically modifies the loop control variable.
Example of a for
Loop
Here’s a simple example demonstrating how to use a for
loop to print the numbers from 0
to 4
:
public class ForLoopExample {
public static void main(String[] args) {
// Using a for loop to iterate from 0 to 4
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
Explanation
- Initialization:
int i = 0;
initializes the loop control variablei
to0
. - Condition:
i < 5;
checks ifi
is less than5
. If true, the loop body will execute. - Loop Body:
System.out.println("Iteration: " + i);
prints the current value ofi
. - Update:
i++
increments the value ofi
by1
at the end of each iteration.
Iteration Breakdown
- 1st Iteration:
i = 0
, the condition0 < 5
istrue
, so it printsIteration: 0
. - 2nd Iteration:
i = 1
, the condition1 < 5
istrue
, so it printsIteration: 1
. - 3rd Iteration:
i = 2
, the condition2 < 5
istrue
, so it printsIteration: 2
. - 4th Iteration:
i = 3
, the condition3 < 5
istrue
, so it printsIteration: 3
. - 5th Iteration:
i = 4
, the condition4 < 5
istrue
, so it printsIteration: 4
. - 6th Iteration:
i = 5
, the condition5 < 5
isfalse
, so the loop terminates.
Output
The output of the above program will be:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Summary
The for
loop is a powerful control structure in Java that allows for concise iteration over a range of values. It is ideal for scenarios where you know in advance how many times you want to execute a block of code. By using the initialization, condition, and update expressions, you can easily control the flow of execution. Understanding how to effectively use for
loops is essential for programming in Java.