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:

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

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

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

Flowchart of For Loop:

Flowchart of For Loop in Java

Detailed Explanation:

By mastering the for loop, developers can efficiently iterate over data and control the flow of their Java programs.