Java Loops for Repeated Execution

Java loops are control flow statements that repeatedly execute a block of code while a condition is true or while elements are available for iteration. Loops are used for counting, traversing arrays, processing collections, printing patterns, reading input repeatedly, and avoiding duplicated code.

This tutorial explains the main loop statements in Java:

  1. for loop – useful when the number of iterations is known or counter-based.
  2. while loop – useful when repetition depends on a condition that may change during execution.
  3. do-while loop – useful when the loop body must execute at least once.
  4. Enhanced for loop – useful for reading each element of an array or collection.
  5. Nested loops – useful for tables, matrices, and repeated work inside repeated work.

Each section includes syntax, a Java program using Example as the class name, output, and a direct explanation of how the loop executes.

How Java Loop Statements Work

A Java loop usually has a starting state, a condition, a loop body, and an update step. The condition decides whether another iteration should run. If the loop condition never becomes false, the loop can become an infinite loop.

Java loopCondition checkedBest use case
forBefore each iterationKnown number of iterations or index-based traversal
whileBefore each iterationRepeat until a condition changes
do-whileAfter each iterationRun the body at least once
Enhanced forFor each elementRead all values from an array or collection
Nested loopsDepends on outer and inner loopsTables, matrices, grids, and patterns

For a language-reference explanation of the for statement, you may also refer to Oracle’s official Java tutorial on the for statement.

1 Java For Loop Syntax and Example

The for loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement.

Syntax:

</>
Copy
for(initialization; condition; update) {
    // code block to be executed
}
  • initialization runs once before the loop starts.
  • condition is checked before each iteration.
  • update runs after each iteration.

Example: This program prints numbers 1 to 5 using a for loop.

</>
Copy
public class Example {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Explanation: The loop initializes i to 1, checks if i is less than or equal to 5, prints the current iteration, and increments i by 1 after each iteration.

A for loop is also commonly used to access array elements by index, especially when the position of each element matters.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int[] marks = {76, 82, 91};

        for (int index = 0; index < marks.length; index++) {
            System.out.println("Index " + index + ": " + marks[index]);
        }
    }
}
Index 0: 76
Index 1: 82
Index 2: 91

2 Java While Loop Syntax and Example

The while loop executes a block of code as long as the specified condition remains true. It is useful when the number of iterations is not known in advance.

Syntax:

</>
Copy
while(condition) {
    // code block to be executed
}

Since the condition is checked before the loop body, a while loop may execute zero times if the condition is false at the beginning.

Example: This program prints numbers 1 to 5 using a while loop.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation: The loop starts with i set to 1 and continues to execute as long as i is less than or equal to 5. After each iteration, i is incremented by 1.

If the update statement i++ is removed, the value of i stays 1 and the loop condition remains true. This creates an infinite loop.

3 Java Do-While Loop Syntax and Example

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once before the condition is tested.

Syntax:

</>
Copy
do {
    // code block to be executed
} while (condition);

The semicolon after while (condition) is required in a do-while loop.

Example: This program prints numbers 1 to 5 using a do-while loop.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Value: " + i);
            i++;
        } while (i <= 5);
    }
}

Output:

Value: 1
Value: 2
Value: 3
Value: 4
Value: 5

Explanation: The do-while loop executes the code block first, then checks the condition. This ensures that the code inside the loop is executed at least once even if the condition is false initially.

4 Enhanced For Loop in Java for Arrays and Collections

The enhanced for loop, also known as the for-each loop, is used for iterating over arrays or collections. It provides a simpler and more readable syntax when you do not need to modify the array or collection.

Syntax:

</>
Copy
for(dataType item : array) {
    // code block to be executed
}

Example: This program iterates through an array of integers and prints each element.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int num : numbers) {
            System.out.println("Number: " + num);
        }
    }
}

Output:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

Explanation: The enhanced for loop automatically iterates over each element in the numbers array and assigns it to the variable num during each iteration.

Use the enhanced for loop when you only need the element value. Use a normal for loop when you need the index, need to update an array element by position, or need to iterate in reverse order.

5 Nested Loops in Java for Tables, Matrices, and Patterns

Nested loops are loops inside other loops. They are useful for iterating over multi-dimensional arrays or performing repeated operations within each iteration of an outer loop.

Example: This program uses nested loops to print a multiplication table for numbers 1 to 3.

</>
Copy
public class Example {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print((i * j) + " ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3 
2 4 6 
3 6 9

Explanation: The outer loop iterates through the numbers 1 to 3. For each iteration of the outer loop, the inner loop iterates through the numbers 1 to 3, multiplying the outer loop variable i by the inner loop variable j and printing the product.

In nested loops, the inner loop usually completes all its iterations for each single iteration of the outer loop. If the outer loop runs 3 times and the inner loop runs 3 times each time, the inner loop body runs 3 * 3 = 9 times.

Java Loop Control Statements: break and continue

The break and continue statements change the normal flow of a loop. break exits the nearest loop immediately. continue skips the remaining statements in the current iteration and moves to the next iteration.

Using break to stop a Java loop early

</>
Copy
public class Example {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println(i);
        }
    }
}
1
2
3

Using continue to skip one Java loop iteration

</>
Copy
public class Example {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println(i);
        }
    }
}
1
2
4
5

Common Java Loop Mistakes and Fixes

  • Infinite loop: Make sure the loop condition can become false. In counter loops, check that the counter is updated correctly.
  • Off-by-one error: Check whether the loop should use < or <=. For arrays, indexes run from 0 to array.length - 1.
  • Wrong loop choice: Do not use enhanced for when you need the current index or need to replace values by index.
  • Missing semicolon in do-while: Remember that do { ... } while (condition); ends with a semicolon.

Choosing the Right Java Loop Statement

Choose a for loop when the repetition is counter-based. Choose a while loop when repetition depends on a condition becoming false. Choose a do-while loop when the loop body must run at least once. Choose an enhanced for loop when you only need to read each element in an array or collection.

Java Loops FAQ

What are the types of loops in Java?

The main loop types in Java are for, while, do-while, and enhanced for. You can also create nested loops by placing one loop inside another loop.

What is the difference between while and do-while loops in Java?

A while loop checks the condition before running the loop body, so it may run zero times. A do-while loop runs the body first and checks the condition afterward, so it always runs at least once.

When should I use a for loop instead of a while loop in Java?

Use a for loop when initialization, condition checking, and update logic are naturally tied to a counter. Use a while loop when the number of iterations is not known in advance.

Can a Java loop run forever?

Yes. A loop can run forever if its condition never becomes false. This usually happens when the variable used in the loop condition is not updated correctly.

Is the enhanced for loop suitable for changing array values?

The enhanced for loop is best for reading values. If you need to change array elements by index, use a normal for loop.

QA Checklist for This Java Loops Tutorial

  • Confirm that every Java program compiles with the class name Example.
  • Check that each output block exactly matches the preceding program.
  • Verify that syntax-only code blocks use language-java syntax and output blocks use output.
  • Confirm that the tutorial explains initialization, condition, update, and loop body clearly.
  • Check that beginner mistakes such as infinite loops, off-by-one errors, and the do-while semicolon are covered.

Summary of Java Loop Statements

In this Java Tutorial, we explored the main loop statements in Java: for, while, do-while, enhanced for, and nested loops. A for loop is useful for counter-based repetition, a while loop is useful for condition-based repetition, a do-while loop is useful when the body must execute at least once, and an enhanced for loop is useful for reading array or collection elements. Choosing the correct loop makes Java code easier to read, test, and maintain.