Java · Module 3 · Lesson 21 min read

Loops

for loop — when you know how many times

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

Three parts: start int i = 1, condition i <= 5, update i++.

while loop — while a condition is true

Java
int lives = 3;
while (lives > 0) {
    System.out.println("Lives: " + lives);
    lives--;
}

do-while — runs at least once

Java
int choice;
do {
    choice = showMenu();
} while (choice != 0);

The condition is checked after the body, which makes it perfect for menus.

Enhanced for (for-each)

Java
String[] langs = {"Java", "Kotlin", "Dart"};
for (String lang : langs) {
    System.out.println(lang);
}

Easy to read, but you don't get the index.

break and continue

  • break → exits the loop immediately.
  • continue → skips to the next round.
  • Labeled break exits outer loops: outer: for (...) { for (...) { break outer; } }

Watch out for infinite loops ⚠️

If the condition never becomes false (for example, you forget lives--), the loop runs forever.

Example

Java
public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0)      System.out.println("FizzBuzz");
            else if (i % 3 == 0)  System.out.println("Fizz");
            else if (i % 5 == 0)  System.out.println("Buzz");
            else                  System.out.println(i);
        }
    }
}