Mastering the Java For Loop: Efficient Iteration in Java
Learn how to use the for
loop in Java for precise control over iteration. Ideal for situations where the number of iterations is known, the for
loop provides a clear and concise syntax for executing a block of code multiple times. Explore its syntax, examples, and best practices to enhance your Java programming skills.
Java For Loop
When you know the number of iterations, use a for loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1: Executed once before the loop starts.
Statement 2: Condition for running the loop.
Statement 3: Executed after each loop iteration.
Example 1
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Output
0
1
2
3
4
Example explained:
Statement 1 sets the variable (int i = 0).
Statement 2 checks the condition (i < 5).
Statement 3 increments the variable (i++).
Example 2
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
Output
0
2
4
6
8
10
Java For Loop Examples
Here are practical examples of the for loop:
Example 1: Counting by Tens
for (int i = 0; i <= 100; i += 10) {
System.out.println(i);
}
Output
0
10
20
30
40
50
60
70
80
90
100
Example 2: Even Numbers
for (int i = 0; i <= 10; i += 2) {
System.out.println(i);
}
Output
0
2
4
6
8
10
Example 3: Multiplication Table
int multiplier = 2;
// Print the multiplication table for the number 2
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (multiplier * i));
}
Output
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20