Java Loops

while, do-while, for and for-each.

✍️ 2 exercises in this lesson
  • while (condition) { }
  • do { } while (condition);: runs at least once
  • for (int i = 0; i < 5; i++) { }
  • for (String s : array) { }: the for-each loop

break exits a loop; continue skips to the next iteration.

Key Takeaways: Java Loops

Mastering Java Loops helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Loops Code Example

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("9 x " + i + " = " + 9 * i);
        }

        int n = 3;
        while (n > 0) {
            System.out.println("Countdown " + n);
            n--;
        }

        String[] langs = {"Java", "Kotlin", "Scala"};
        for (String lang : langs) {
            if (lang.equals("Kotlin")) continue;
            System.out.println(lang);
        }
    }
}
Output
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
Countdown 3
Countdown 2
Countdown 1
Java
Scala
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Loops Practice Exercises

Check what you learned in “Java Loops”.

/ 2 solved
Fill in the blank

Loop over every element (for-each).

for (String s  names) { }
✓ Correct! Not quite. Try again.
Multiple choice

Which keyword exits a loop early?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services