Repeating an action without copying the same code over and over is one of the first real superpowers a new programmer gains, and Java provides three main loop types, each suited to a slightly different situation.

The for loop

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

A for loop is the natural choice when the number of repetitions is known ahead of time. It has three parts separated by semicolons: a starting value, a condition checked before every pass, and a step that runs after each pass, here incrementing i by one.

The while loop

int count = 0;
while (count < 3) {
  System.out.println(count);
  count++;
}

A while loop fits better when the number of repetitions is not known upfront and instead depends on some condition becoming false, such as reading input until the user chooses to stop.

The do-while loop

A do-while loop is a close relative of while, except it checks its condition after running the block rather than before, guaranteeing the body runs at least once:

int attempts = 0;
do {
  attempts++;
} while (attempts < 1);

The for-each loop

For visiting every item in an array or a collection, the for-each loop reads the most naturally, since there is no index to manage manually:

for (String fruit : fruits) {
  System.out.println(fruit);
}

break and continue

Two keywords let a loop change course early. break exits the loop entirely, useful once a search has already found what it was looking for. continue skips straight to the next repetition without finishing the current one:

for (int i = 0; i < items.size(); i++) {
  if (items.get(i) == null) continue;
  if (items.get(i).equals(target)) break;
}

Nested loops

A loop can contain another loop, commonly used for working through a grid of values, such as rows and columns:

for (int row = 0; row < 3; row++) {
  for (int col = 0; col < 3; col++) {
    System.out.print(row + "," + col + " ");
  }
}

Avoiding endless loops

Every loop needs a way to eventually stop. A while loop whose condition never becomes false, or a for loop whose step never moves the counter toward its limit, runs forever and freezes the program. Whenever a loop behaves unexpectedly, checking that its stopping condition can genuinely be reached is usually the first thing worth verifying.

Choosing between them

Reach for a for loop when the repeat count is known, a while loop when it depends on a changing condition, and a for-each loop whenever the goal is simply to visit every item in a collection without needing its position.