The for loop in Java is used to execute a block of code a fixed number of times. It is commonly used when the number of iterations is known in advance.
The Java for loop consists of three parts:
// Basic syntax of a for loop
for(initialization; condition; update){
// code to be executed repeatedly
}
// Print numbers from 1 to 5 using for loop
class ForLoopDemo {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
1
2
3
4
5
The loop starts with i = 1, runs while i <= 5, and increments i after each iteration.
Modify the values below and run the code to see how the Java loop behaves logically:
for loop when iteration count is fixed