Java Programming Handbook

    Java For Loop

    In Java, a for loop is one of the most commonly used control flow statements. It allows you to repeatedly execute a block of code for a fixed number of iterations. This makes it an essential tool for performing repetitive tasks, especially when you know in advance how many times you need to execute a particular statement or block of code.

    In this blog, we’ll explore how the for loop works, its syntax, and provide examples to help you understand its usage clearly.

    What is a For Loop?#

    The for loop is used when you know the number of iterations you need to execute. It is ideal for iterating through collections, arrays, or performing repetitive tasks.

    Syntax of a For Loop#

    for(initialization; condition; update) { // Code to be executed }
    • initialization: This step is executed once, before the loop starts. It is typically used to initialize loop control variables.
    • condition: This is evaluated before each iteration. If the condition evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.
    • update: After each iteration, the update statement is executed. It is typically used to modify the loop control variable (like incrementing or decrementing).

    Flow Chart:

    For loop flow chart

    Basic Example of a For Loop#

    Let’s start with a simple example to demonstrate the basic structure of a for loop.

    Example 1: Print Numbers from 1 to 5#

    class Main { public static void main(String[] args) { // Using a for loop to print numbers from 1 to 5 for (int i = 1; i <= 5; i++) { System.out.println(i); } } }

    Explanation:

    • Initialization: int i = 1 sets the starting value of i to 1.
    • Condition: i <= 5 checks if i is less than or equal to 5.
    • Update: i++ increments i by 1 after each iteration.
    • This loop prints the numbers from 1 to 5.

    Expected Output:

    1 2 3 4 5

    For Loop with Multiple Statements#

    You can also have multiple statements in the initialization, condition, or update sections of a for loop. This is useful when you need to modify more than one variable.

    Example 2: Multiple Statements in For Loop#

    class Main { public static void main(String[] args) { // Using a for loop with multiple statements for (int i = 1, j = 10; i <= 5; i++, j -= 2) { System.out.println("i: " + i + ", j: " + j); } } }

    Explanation:

    • Initialization: int i = 1, j = 10 initializes two variables, i and j.
    • Condition: i <= 5 checks if i is less than or equal to 5.
    • Update: i++ increments i by 1, and j -= 2 decrements j by 2 after each iteration.
    • This loop prints the values of i and j in each iteration.

    Expected Output:

    i: 1, j: 10 i: 2, j: 8 i: 3, j: 6 i: 4, j: 4 i: 5, j: 2

    For Loop with Arrays#

    A for loop is frequently used to iterate through arrays. This is useful when you need to perform an operation on each element in the array.

    Example 3: Iterate Through an Array#

    class Main { public static void main(String[] args) { int[] numbers = {2, 4, 6, 8, 10}; // Using a for loop to iterate through the array for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } }

    Explanation:

    • Initialization: int i = 0 starts the loop at the first element of the array.
    • Condition: i < numbers.length ensures the loop continues as long as i is less than the length of the array.
    • Update: i++ increments i by 1 in each iteration.
    • The loop prints each element in the numbers array.

    Expected Output:

    Element at index 0: 2 Element at index 1: 4 Element at index 2: 6 Element at index 3: 8 Element at index 4: 10

    For Loop with a Decrementing Counter#

    A for loop can also be used to count downwards, by using a decrementing counter. This is useful when you need to execute a block of code in reverse order.

    Example 4: Count Downwards from 5#

    class Main { public static void main(String[] args) { // Using a for loop to count down from 5 to 1 for (int i = 5; i > 0; i--) { System.out.println(i); } } }

    Explanation:

    • Initialization: int i = 5 starts the loop at 5.
    • Condition: i > 0 ensures the loop runs while i is greater than 0.
    • Update: i-- decrements i by 1 after each iteration.
    • The loop prints numbers from 5 to 1 in reverse order.

    Expected Output:

    5 4 3 2 1

    Infinite For Loop#

    A for loop can be set to run infinitely by leaving out the condition, or setting it to always be true. This is generally used when you need a loop to run indefinitely until a break condition is met.

    Example 5: Infinite For Loop#

    class Main { public static void main(String[] args) { // Infinite for loop for (;;) { System.out.println("This will print forever!"); break; // Breaking out of the infinite loop } } }

    Explanation:

    • The for(;;) creates an infinite loop, since the condition is always true.
    • The break statement immediately exits the loop after the first print statement.
    • Without the break, the loop would run forever.

    Expected Output:

    This will print forever!

    For-Each Loop (Enhanced For Loop)#

    In addition to the traditional for loop, Java also provides a for-each loop to simplify the iteration over arrays or collections.

    Example 6: For-Each Loop#

    class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; // Using a for-each loop to iterate through the array for (int num : numbers) { System.out.println(num); } } }

    Explanation:

    • The for-each loop simplifies iterating over an array.
    • It automatically accesses each element in the array one by one, without needing an index.

    Expected Output:

    1 2 3 4 5

    Conclusion#

    In this blog, we learned:

    • The for loop is a fundamental control flow statement in Java used for iterating over a fixed number of iterations.
    • We explored how to use the for loop with initialization, conditions, and updates.
    • We also learned how to use the for loop with arrays and collections, as well as for counting upwards or downwards.
    • Additionally, we looked at the for-each loop as a simpler way to iterate over arrays.

    Mastering the for loop is crucial for efficient coding, especially when you need to perform repetitive tasks in a concise and readable manner.

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more

    Last updated on Apr 09, 2025

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.