Java Loops
Repeat work without copy-pasting code.
for loop
The most common loop. Three parts: initialization, condition, increment.
for loop
for (int i = 0; i < 5; i++) { System.out.println("Count: " + i); } // Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
while loop
Repeats while a condition is true. Check happens before each iteration.
while loop
int n = 10; while (n > 0) { System.out.println(n); n--; } System.out.println("Liftoff!");
do-while loop
Like while, but the body executes at least once — the check is at the bottom.
do-while
int n = 0; do { System.out.println("Runs once even if false"); n++; } while (n < 0); // false from the start, but body still ran once
for-each loop (enhanced for)
Cleanest way to iterate over arrays and collections — no index management:
for-each
String[] names = {"Raman", "Aman", "Priya"}; for (String name : names) { System.out.println(name); }
Read it as: "for each String called name in names".
Which loop should I use?
- Need the index? Use
for. - Iterating a collection or array? Use for-each.
- Loop count unknown, depends on a condition? Use
while. - Need to run at least once?
do-while(rare).
break — exit a loop early
break
for (int i = 0; i < 10; i++) { if (i == 5) break; System.out.println(i); } // 0 1 2 3 4
continue — skip to next iteration
continue
for (int i = 0; i < 5; i++) { if (i % 2 == 0) continue; // skip even numbers System.out.println(i); } // 1 3
Nested loops
Multiplication table
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.print(i * j + " "); } System.out.println(); } // 1 2 3 // 2 4 6 // 3 6 9
Beware infinite loops
while (true) with no break runs forever. for (int i=0; i<n; i--) never terminates because i goes the wrong way. Always make sure your condition can become false.