Java for Loop

The for loop in Java is used to repeatedly execute a block of code a specific number of times. It is ideal when you know in advance how many times the loop should run.

1. Syntax of for Loop

for (initialization; condition; update) {
    // Code to be executed
}
  • Initialization: This part runs once at the beginning of the loop and is used to initialize variables.
  • Condition: This is a boolean expression that is evaluated before each iteration. If it evaluates to true, the loop body is executed; if false, the loop terminates.
  • Update: This is executed after each iteration, typically used to increment or decrement the loop variable.

2. Example of a for Loop

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4

In this example:

  • The loop initializes the variable i to 0.
  • It checks the condition i < 5 before each iteration.
  • After each iteration, i is incremented by 1 using i++.

The loop runs until i becomes 5, at which point the condition becomes false, and the loop terminates.

3. The for Loop Explained

  • Initialization (int i = 0): The loop starts with i initialized to 0.
  • Condition (i < 5): The loop continues as long as i is less than 5.
  • Update (i++): After each iteration, i is incremented by 1.

4. Different Variations of the for Loop

Counting Backwards

You can use a for loop to count down by decrementing the variable.

public class Main {
    public static void main(String[] args) {
        for (int i = 5; i > 0; i--) {
            System.out.println(i);
        }
    }
}

Output:

5
4
3
2
1
Skipping Increments

You can skip certain numbers by incrementing the loop variable differently, like using i += 2 to skip every other number.

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i += 2) {
            System.out.println(i);
        }
    }
}

Output:

0
2
4
6
8

5. Nested for Loops

A for loop can be nested inside another for loop. This is useful when working with multi-dimensional data or performing repeated tasks within another loop.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In this case, the outer loop controls the value of i, and the inner loop controls the value of j. For each value of i, the inner loop runs completely before the outer loop moves to the next iteration.

6. break and continue in a for Loop

You can control the flow of the for loop using break and continue.

Breaking Out of a for Loop

The break statement is used to exit the loop entirely, even if the loop condition has not been met.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break;  // Exit the loop when i is 5
            }
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4
Skipping Iterations with continue

The continue statement skips the current iteration and jumps to the next iteration without completing the loop body.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                continue;  // Skip the rest of the loop when i is 5
            }
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4
6
7
8
9

Here, when i equals 5, the continue statement skips the System.out.println(i) and moves to the next iteration.

7. Enhanced for Loop (for-each)

Java provides an enhanced for loop, also known as a for-each loop, to iterate over arrays and collections more easily. This is particularly useful when you don’t need to access the index.

Example:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

1
2
3
4
5

The for-each loop automatically iterates over each element in the numbers array and assigns it to the variable number.

8. Infinite for Loop

If the condition in a for loop always evaluates to true, the loop will run indefinitely. Be cautious when writing loop conditions to avoid infinite loops.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; ; i++) {  // No condition
            System.out.println(i);
        }
    }
}

This loop will keep printing values of i indefinitely unless you stop the program manually.

9. Summary

  • The for loop is ideal when the number of iterations is known.
  • It consists of three parts: initialization, condition, and update.
  • You can control the flow of the loop using break (to exit) and continue (to skip).
  • Use the enhanced for loop for easy iteration over arrays or collections.
  • Be cautious of infinite loops by ensuring the loop’s condition eventually becomes false.

The for loop is a versatile tool for controlling repeated actions in your code, offering flexibility and control over how many times you want a task to be repeated.

Java for Loop

The for loop in Java is used to repeatedly execute a block of code a specific number of times. It is ideal when you know in advance how many times the loop should run.

1. Syntax of for Loop

for (initialization; condition; update) {
    // Code to be executed
}
  • Initialization: This part runs once at the beginning of the loop and is used to initialize variables.
  • Condition: This is a boolean expression that is evaluated before each iteration. If it evaluates to true, the loop body is executed; if false, the loop terminates.
  • Update: This is executed after each iteration, typically used to increment or decrement the loop variable.

2. Example of a for Loop

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4

In this example:

  • The loop initializes the variable i to 0.
  • It checks the condition i < 5 before each iteration.
  • After each iteration, i is incremented by 1 using i++.

The loop runs until i becomes 5, at which point the condition becomes false, and the loop terminates.

3. The for Loop Explained

  • Initialization (int i = 0): The loop starts with i initialized to 0.
  • Condition (i < 5): The loop continues as long as i is less than 5.
  • Update (i++): After each iteration, i is incremented by 1.

4. Different Variations of the for Loop

Counting Backwards

You can use a for loop to count down by decrementing the variable.

public class Main {
    public static void main(String[] args) {
        for (int i = 5; i > 0; i--) {
            System.out.println(i);
        }
    }
}

Output:

5
4
3
2
1
Skipping Increments

You can skip certain numbers by incrementing the loop variable differently, like using i += 2 to skip every other number.

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i += 2) {
            System.out.println(i);
        }
    }
}

Output:

0
2
4
6
8

5. Nested for Loops

A for loop can be nested inside another for loop. This is useful when working with multi-dimensional data or performing repeated tasks within another loop.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In this case, the outer loop controls the value of i, and the inner loop controls the value of j. For each value of i, the inner loop runs completely before the outer loop moves to the next iteration.

6. break and continue in a for Loop

You can control the flow of the for loop using break and continue.

Breaking Out of a for Loop

The break statement is used to exit the loop entirely, even if the loop condition has not been met.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break;  // Exit the loop when i is 5
            }
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4
Skipping Iterations with continue

The continue statement skips the current iteration and jumps to the next iteration without completing the loop body.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                continue;  // Skip the rest of the loop when i is 5
            }
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4
6
7
8
9

Here, when i equals 5, the continue statement skips the System.out.println(i) and moves to the next iteration.

7. Enhanced for Loop (for-each)

Java provides an enhanced for loop, also known as a for-each loop, to iterate over arrays and collections more easily. This is particularly useful when you don’t need to access the index.

Example:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

1
2
3
4
5

The for-each loop automatically iterates over each element in the numbers array and assigns it to the variable number.

8. Infinite for Loop

If the condition in a for loop always evaluates to true, the loop will run indefinitely. Be cautious when writing loop conditions to avoid infinite loops.

Example:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; ; i++) {  // No condition
            System.out.println(i);
        }
    }
}

This loop will keep printing values of i indefinitely unless you stop the program manually.

9. Summary

  • The for loop is ideal when the number of iterations is known.
  • It consists of three parts: initialization, condition, and update.
  • You can control the flow of the loop using break (to exit) and continue (to skip).
  • Use the enhanced for loop for easy iteration over arrays or collections.
  • Be cautious of infinite loops by ensuring the loop’s condition eventually becomes false.

The for loop is a versatile tool for controlling repeated actions in your code, offering flexibility and control over how many times you want a task to be repeated.