Java - Loops

Loops

for

for (int i = 0; i < 3; i++) {
  System.out.println(i);
}

while / do-while

int j = 0;
while (j < 3) { j++; }

do { j--; } while (j > 0);

Enhanced for (for-each)

int[] arr = {1,2,3};
for (int v : arr) {
  System.out.println(v);
}

break, continue, and labels

outer:
for (int r = 0; r < 3; r++) {
  for (int c = 0; c < 3; c++) {
    if (r == c) continue; // skip diagonal
    if (r + c > 3) break outer; // exit both loops
  }
}

Iteration Patterns

  • Counting loops
  • Searching until found (break early)
  • Aggregations (sum, min/max)
Prefer enhanced for or streams when index is not required to avoid off-by-one errors.

Try it

  1. Sum an array using a for loop, then using an enhanced for-each.
  2. Write a nested loop and break out of both loops with a label when a condition is met.