For Loop in Java | Control Flow in Java
The for loop in Java is a control flow statement that allows code to be executed repeatedly based on a boolean condition. It's widely used for iterating over a range of values or collections.
Key Points on For Loop:
- The for loop consists of three parts: initialization, condition, and increment/decrement.
- It’s ideal when the number of iterations is known beforehand.
- Nested for loops can be used for multi-dimensional data structures, such as arrays.
- Control statements like break and continue can alter the flow of the loop.
- The loop variable has a scope limited to the loop itself, preventing interference with other code.
- It can iterate through collections, making it versatile for different data types.
- Performance can be affected by the complexity of the loop and the operations inside it.
- Complex conditions can be included, allowing for more nuanced loop behavior.
- Infinite loops can occur if the loop condition never becomes false; use with caution.
Syntax of For Loop:
Syntax Example
for (initialization; condition; increment) {
// Code to execute in each iteration
}
Example of For Loop in Java:
This example demonstrates a basic for loop that prints numbers from 1 to 5.
Code Example 1
public class PrintNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output for Code Example 1:
1
2
3
4
5
2
3
4
5
Example of Nested For Loop:
This example uses a nested for loop to print a multiplication table.
Code Example 2
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + " ");
}
System.out.println(); // Move to the next line after inner loop
}
}
}
Output for Code Example 2:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Using Control Statements:
This example shows how to use the break statement in a for loop.
Code Example 3
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}
}
}
Output for Code Example 3:
1
2
3
4
2
3
4
Flowchart of For Loop:

Detailed Explanation:
- Initialization: This sets the starting point of the loop, usually defining the loop variable.
- Condition: The loop continues as long as this condition is true. If false, the loop exits.
- Increment/Decrement: This modifies the loop variable, determining how the loop progresses toward its termination.
- Nested For Loops: Allows for multiple iterations, useful for handling multi-dimensional data.
By mastering the for loop, developers can efficiently iterate over data and control the flow of their Java programs.