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
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}The brackets hold three parts, separated by semicolons:
- Start:
int i = 1creates a counter. - Condition:
i <= 5is checked before every pass. When it's false, the loop ends. - 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:
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:
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:
String[] colours = {"red", "green", "blue"};
System.out.println(colours[0]); // red
System.out.println(colours.length); // 3Positions start at 0, and .length gives the size. To visit every item, the enhanced for loop is the clearest option:
for (String colour : colours) {
System.out.println(colour);
}Read it as "for each colour in colours".
break and continue
breakstops the loop immediately.continueskips 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:
| Pattern | Idea | Typical code |
|---|---|---|
| Accumulate | Build a total as you go | total += price; |
| Count | Count items that match a condition | if (score >= 50) passed++; |
| Find the largest | Keep the best value seen so far | if (x > max) max = x; |
| Search | Stop as soon as the item is found | if (name.equals(target)) { found = true; break; } |
| Validate input | Repeat until the input is acceptable | do { ... } 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
| Situation | Loop |
|---|---|
| A known number of repetitions, or you need the index | for |
| Every item of an array or list, without the index | enhanced for |
| Repeat until something changes, number unknown | while |
| The body must run at least once | do-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-whilealways runs once.- Arrays like
int[] nums = {1, 2, 3};start at index 0 and have a.length. for (Type item : array)visits every element.breakexits a loop;continueskips to the next pass.
Java Loops Examples
Each example shows the code, the output it produces and what each part does.
Countdown and times table
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));
}
}
}3...
2...
1...
Go!
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18Line-by-line explanation
- Line 3Start at 3, keep going while i is above 0, subtract 1 each time.
- Line 8A second loop counting up from 1 to 3.
Total and average of an array
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);
}
}Items: 4
Total: 28.5
Average: 7.125Line-by-line explanation
- Line 3An array of four doubles.
- Lines 6 to 8The enhanced for loop adds each price to the running total.
- Line 12Divide by the number of items to get the average.
while with break and continue
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);
}
}1 2 4 5 7 8
Stopped at 10Line-by-line explanation
- Line 4while (true) would run forever, so the loop relies on break.
- Lines 6 to 8Multiples of 3 are skipped by continue.
- 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
int[] nums = {5, 6, 7};
for (int i = 0; i <= nums.length; i++) {
System.out.println(nums[i]);
}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
int count = 0;
while (count < 5) {
System.out.println(count);
}int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}Semicolon after the for line
for (int i = 0; i < 3; i++); {
System.out.println("Hi");
}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.
Complete the loop so it prints 0, 1, 2, 3 and 4.
(int i = 0; i < 5; ) {
System.out.println(i);
}
How many times does this print "Hi"?
for (int i = 2; i <= 10; i += 2) {
System.out.println("Hi");
}
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);
Which loop always runs its body at least once?
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.
What is the index of the first element of a Java array?
- 1
- 0
- -1
- It depends on the type
What does
continuedo 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
How do you get the number of elements in an array named
items?- items.size()
- items.count
- items.length
- length(items)
What is the last value of
iprinted byfor (int i = 0; i < 10; i += 3) System.out.println(i);?- 6
- 10
- 12
- 9
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