Java Loops

Repeat code with for, while, do-while and the enhanced for loop, and control loops with break and continue.

Lesson 22 of 127Beginner17 min read

Loops let a program repeat work without repeating code. Print a times table, add up a list of prices, keep asking for a password until it's right: all of these are loops.

Java has three main loops. The for loop is ideal when you know how many times to repeat. The while loop repeats as long as a condition stays true. The enhanced for loop, also called for-each, visits every item in an array or list. There's also a do-while loop that always runs at least once.

In this lesson you'll use each kind, meet arrays, the simplest way to store several values, and learn to steer loops with break and continue.

The for loop

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

The brackets hold three parts, separated by semicolons:

  1. Start: int i = 1 creates a counter.
  2. Condition: i <= 5 is checked before every pass. When it's false, the loop ends.
  3. Update: i++ adds 1 to the counter after every pass.

Counters are usually called i, and you can count down too: for (int i = 10; i > 0; i--).

while and do-while

A while loop checks its condition before each pass:

Java
int balance = 100;
while (balance > 0) {
    balance -= 30;
}

A do-while loop checks after each pass, so its body always runs at least once. It's handy for menus and "ask again" prompts:

Java
do {
    // show the menu and read a choice
} while (choice != 0);

Inside any while loop, something must eventually make the condition false. Otherwise the loop never ends.

Arrays and the enhanced for loop

An array holds a fixed number of values of one type:

Java
String[] colours = {"red", "green", "blue"};
System.out.println(colours[0]);      // red
System.out.println(colours.length);  // 3

Positions start at 0, and .length gives the size. To visit every item, the enhanced for loop is the clearest option:

Java
for (String colour : colours) {
    System.out.println(colour);
}

Read it as "for each colour in colours".

break and continue

  • break stops the loop immediately.
  • continue skips the rest of the current pass and moves on to the next one.

Both work in every kind of loop. Use them sparingly: a loop whose stopping rule is visible in its condition is easier to follow.

Common loop patterns

Most loops you write follow a handful of patterns. Recognising them makes new problems much easier:

PatternIdeaTypical code
AccumulateBuild a total as you gototal += price;
CountCount items that match a conditionif (score >= 50) passed++;
Find the largestKeep the best value seen so farif (x > max) max = x;
SearchStop as soon as the item is foundif (name.equals(target)) { found = true; break; }
Validate inputRepeat until the input is acceptabledo { ... } while (!valid);

Each pattern needs a starting value before the loop: 0 for a total or count, and the first element for a maximum. Starting max at 0 is a classic bug, because it gives the wrong answer when every value is negative.

Choosing the right loop

SituationLoop
A known number of repetitions, or you need the indexfor
Every item of an array or list, without the indexenhanced for
Repeat until something changes, number unknownwhile
The body must run at least oncedo-while

The companion lessons on loop types, nested and enhanced loops and break and continue practise each loop in more detail.

Java Loops Syntax

Loop syntax

for (int i = 0; i < n; i++) { }

while (condition) { }

do { } while (condition);

for (Type item : array) { }

Java Loops Summary

  • for (start; condition; update) repeats a known number of times.
  • while (condition) repeats while the condition is true; do-while always runs once.
  • Arrays like int[] nums = {1, 2, 3}; start at index 0 and have a .length.
  • for (Type item : array) visits every element.
  • break exits a loop; continue skips to the next pass.

Java Loops Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Countdown and times table

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 3; i > 0; i--) {
            System.out.println(i + "...");
        }
        System.out.println("Go!");

        for (int i = 1; i <= 3; i++) {
            System.out.println("6 x " + i + " = " + (6 * i));
        }
    }
}
Output
3...
2...
1...
Go!
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
Line-by-line explanation
  1. Line 3Start at 3, keep going while i is above 0, subtract 1 each time.
  2. Line 8A second loop counting up from 1 to 3.
Example 2

Total and average of an array

Java
public class Main {
    public static void main(String[] args) {
        double[] prices = {4.50, 12.00, 3.25, 8.75};
        double total = 0;

        for (double price : prices) {
            total += price;
        }

        System.out.println("Items: " + prices.length);
        System.out.println("Total: " + total);
        System.out.println("Average: " + total / prices.length);
    }
}
Output
Items: 4
Total: 28.5
Average: 7.125
Line-by-line explanation
  1. Line 3An array of four doubles.
  2. Lines 6 to 8The enhanced for loop adds each price to the running total.
  3. Line 12Divide by the number of items to get the average.
Example 3

while with break and continue

Java
public class Main {
    public static void main(String[] args) {
        int n = 0;
        while (true) {
            n++;
            if (n % 3 == 0) {
                continue;
            }
            if (n > 8) {
                break;
            }
            System.out.print(n + " ");
        }
        System.out.println();
        System.out.println("Stopped at " + n);
    }
}
Output
1 2 4 5 7 8 
Stopped at 10
Line-by-line explanation
  1. Line 4while (true) would run forever, so the loop relies on break.
  2. Lines 6 to 8Multiples of 3 are skipped by continue.
  3. Lines 9 to 11The first number above 8 that isn't skipped is 10, so the loop stops there.

Common Java Loops Mistakes

Going one past the end of an array

Don't
int[] nums = {5, 6, 7};
for (int i = 0; i <= nums.length; i++) {
    System.out.println(nums[i]);
}
Do
int[] nums = {5, 6, 7};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

With <=, the loop tries nums[3], which doesn't exist.

A while loop that never ends

Don't
int count = 0;
while (count < 5) {
    System.out.println(count);
}
Do
int count = 0;
while (count < 5) {
    System.out.println(count);
    count++;
}

Semicolon after the for line

Don't
for (int i = 0; i < 3; i++); {
    System.out.println("Hi");
}
Do
for (int i = 0; i < 3; i++) {
    System.out.println("Hi");
}

The semicolon gives the loop an empty body, so "Hi" prints only once.

Java Loops in Real Projects

Loops in real Java code

A payroll system loops over every employee to calculate wages, a game loops over every enemy to move it each frame, and a server runs a loop that waits for and handles incoming requests. In real projects you'll mostly loop over collections like ArrayList, using the same for-each syntax you learned here.

Java Loops FAQ

What is the difference between a for loop and a while loop in Java?

A for loop keeps the counter, the condition and the update together on one line, which suits a known number of repetitions. A while loop only has a condition, which suits repeating until something changes, such as valid input or the end of a file. Any for loop can be rewritten as a while loop.

How do I loop backwards in Java?

Start at the end and count down: for (int i = arr.length - 1; i >= 0; i--). The condition uses >= 0 so the first element, at index 0, is included.

How do I break out of nested loops?

A plain break only leaves the innermost loop. Put a label before the outer loop, such as outer:, and write break outer; to leave both at once. Moving the nested loops into a method and using return is often clearer.

Can I change an array inside a for-each loop?

Assigning to the loop variable doesn't change the array, because the variable holds a copy of each element. Use an index-based for loop to replace elements. You can, however, call methods on objects in the array, which changes the objects themselves.

How do I write an infinite loop on purpose?

Use while (true) or for (;;), with a break or return inside for the exit. Servers and game loops are written this way. Make sure the exit condition is reachable, or press Ctrl+C in the terminal to stop the program.

Java Loops Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the loop so it prints 0, 1, 2, 3 and 4.

 (int i = 0; i < 5; ) {
    System.out.println(i);
}
Predict the outputeasy

How many times does this print "Hi"?

for (int i = 2; i <= 10; i += 2) {
    System.out.println("Hi");
}
Predict the outputmedium

What does this print?

int[] a = {3, 1, 4, 1, 5};
int max = a[0];
for (int x : a) {
    if (x > max) {
        max = x;
    }
}
System.out.println(max);
Multiple choicemedium

Which loop always runs its body at least once?

Predict the outputmedium

What does this print?

for (int i = 10; i > 0; i -= 3) {
    System.out.print(i + " ");
}

Java Loops Quiz

5 questions to check what you learned.

  1. What is the index of the first element of a Java array?

    • 1
    • 0
    • -1
    • It depends on the type
  2. What does continue do in a loop?

    • Skips the rest of this pass and starts the next one
    • Ends the loop
    • Restarts the loop from the beginning
    • Pauses the program
  3. How do you get the number of elements in an array named items?

    • items.size()
    • items.count
    • items.length
    • length(items)
  4. What is the last value of i printed by for (int i = 0; i < 10; i += 3) System.out.println(i);?

    • 6
    • 10
    • 12
    • 9
  5. How is a do-while loop different from a while loop?

    • It's faster
    • Its body always runs at least once
    • It can't use break
    • It counts automatically