java-bucles-for-while-foreach

Loops in Java: for, while, do-while, and for-each

  • 4 min

A loop is a structure that repeats a block of code while a condition is true.

Humans are terrible at repeating tasks. If I ask you to write “I will not throw paper on the floor” 1,000 times, by the fifth attempt you’ll be bored, and by the tenth you’ll make a mistake.

Computers, however, love it. They can repeat a task millions of times without getting tired or making errors.

To achieve this in programming, we use Loops (or cycles). Today we’ll look at the tools Java provides for repetition: from the classic ones inherited from C to modern and safe versions.

The while loop

It’s the simplest loop. While the condition is true, repeat.

The condition is evaluated before entering. If the condition is false from the start, the code inside never executes.

int counter = 0;

while (counter < 5) {
    System.out.println("Counting: " + counter);
    counter++; // Important! If you forget this, you'll have an infinite loop
}
Copied!

If the condition never becomes false (for example, you forget to increment the counter), the program will hang forever, consuming 100% of your CPU until you kill it.

The do-while loop

It’s the rebellious sibling of while. The key difference is that the condition is evaluated at the end.

This guarantees that the code inside will execute at least once, regardless of whether the condition is true or false.

It’s very useful for user menus, where you first want to show the options and then ask if they want to exit.

Scanner sc = new Scanner(System.in);
int option;

do {
    System.out.println("1. Play");
    System.out.println("0. Exit");
    option = sc.nextInt();
} while (option != 0);

System.out.println("End of game");
Copied!

The classic for loop

When we know in advance how many times we want to repeat something (e.g., “from 0 to 100”), the while can get a bit messy.

The for loop packs all the control logic into a single line. It’s the industry standard for counters.

Syntax: for (initialization; condition; update)

//    Start  ;  Condition ; Step
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration number " + i);
}
Copied!
  1. int i = 0: Runs once at the beginning. Creates the counter variable.
  2. i < 5: Checked before each iteration. If false, we exit.
  3. i++: Executed at the end of each iteration.

By historical convention, loop variables are usually named i, j, k. If you nest loops, use different names to avoid confusion.

The for-each loop

For-each allows you to iterate over data collections (like Arrays or Lists).

Although we’ll cover Arrays in depth in the next article, remember this: The for-each eliminates the need to handle indices and counters. It prevents “out-of-bounds” errors.

It reads as: “For each name in nameList…”.

String[] names = {"Ana", "Luis", "Pedro"};

// Classic Version (Prone to index errors)
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}

// For-Each Version (Clean and safe)
for (String name : names) {
    System.out.println(name);
}
Copied!

Controlling the loop: break and continue

Sometimes we need to alter the normal flow of the loop.

Breaks the loop immediately. It stops executing and jumps out. It’s often used for searches: “If I find what I’m looking for, I stop looking.”

for (int i = 0; i < 1000; i++) {
    if (i == 5) {
        System.out.println("Found 5. I'm out!");
        break; // Exits the loop, never reaches 1000
    }
}
Copied!

Stops the current iteration and jumps to the next check/update. It doesn’t exit the loop, it just skips the remaining code in that specific iteration.

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // Skips the print for 2, but continues with 3
    }
    System.out.println(i);
}
// Output: 0, 1, 3, 4
Copied!