Java Loops

Loops in Java allow you to execute a block of code repeatedly based on a condition. In this tutorial, we’ll explore for, while, and do-while loops.

The for Loop

The for loop is great for running code a specific number of times:

for (int i = 1; i <= 5; i++) {
        System.out.println("Iteration: " + i);
    }

The while Loop

The while loop executes as long as its condition is true:

int count = 1;
    while (count <= 3) {
        System.out.println("Count: " + count);
        count++;
    }

The do-while Loop

The do-while loop runs at least once, even if the condition is false:

int count = 1;
    do {
        System.out.println("Count: " + count);
        count++;
    } while (count <= 3);

Using break and continue

Use break to exit a loop and continue to skip the current iteration:

for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            break; // Exit the loop
        }
        System.out.println(i);
    }
for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue; // Skip this iteration
        }
        System.out.println(i);
    }

Next Steps

Practice each loop type to understand when and where to use them. Loops are a fundamental tool for handling repetitive tasks in programming. Now you can learn about functions!