Java tutorialLesson 7 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Loops: for, while, do-while, Nested Loops, break, and continue
Repeat code in Java with for, while, and do-while loops, build patterns with nested loops, and control loops with break and continue.
- Qyubie Learn Editorial Team
- Published
- 8 min read
Includes 3 quick checks you can do right here.
A loop repeats a block of code: printing a table, adding up scores, asking again until the input is valid. Java has three loops (for, while, and do-while) plus two keywords that change a loop's flow, break and continue.
By the end of this lesson you will be able to:
- write counting loops with
for, - repeat until a condition changes with
whileanddo-while, - choose the right loop for a problem,
- use nested loops for tables and patterns, and
- stop or skip iterations with
breakandcontinue.
The for loop
Use for when you know how many times to repeat. Its header has three parts, separated by semicolons:
for (int i = 1; i <= 5; i++) {
System.out.println("Line " + i);
}Output:
Line 1
Line 2
Line 3
Line 4
Line 5- Initialization (
int i = 1) runs once, before the loop starts. - Condition (
i <= 5) is checked before every repetition; the loop stops when it'sfalse. - Update (
i++) runs after each repetition.
You can count by any step, and in either direction:
for (int i = 10; i > 0; i -= 3) {
System.out.print(i + " ");
}
System.out.println();Output:
10 7 4 1Quick check
The accumulator pattern
Loops often build up a result, such as a sum, a count, or a product. Start a variable before the loop and update it inside:
int sum = 0;
for (int n = 1; n <= 100; n++) {
sum += n;
}
System.out.println("1 + 2 + ... + 100 = " + sum);Output:
1 + 2 + ... + 100 = 5050The while loop
Use while when you don't know how many repetitions you'll need, only the condition for continuing. The condition is checked before each repetition, so the body might run zero times.
int balance = 1000;
int months = 0;
while (balance > 0) {
balance -= 300;
months++;
}
System.out.println("Paid off in " + months + " months");Output:
Paid off in 4 monthsSomething inside the body must eventually make the condition false. Otherwise you get an infinite loop:
int i = 0;
while (i < 5) {
System.out.println(i);
// forgot i++ : prints 0 forever
}The do-while loop
A do-while checks its condition after the body, so the body always runs at least once. That makes it a natural fit for menus and input validation: ask first, then decide whether to ask again.
import java.util.Scanner;
public class ValidScore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int score;
do {
System.out.println("Enter a score from 0 to 100:");
score = in.nextInt();
} while (score < 0 || score > 100);
System.out.println("Saved: " + score);
}
}Output (typing 150, then -5, then 88):
Enter a score from 0 to 100:
Enter a score from 0 to 100:
Enter a score from 0 to 100:
Saved: 88Note the semicolon after while (...) at the end of a do-while. It's required there, unlike in a regular while.
Quick check
Which loop should I use?
| Loop | Checks the condition | Use it when |
|---|---|---|
for | before each repetition | you know the count, or you're stepping through a range |
while | before each repetition | you repeat until something changes; it may run zero times |
do-while | after each repetition | the body must run at least once (menus, input checks) |
Nested loops
A loop inside a loop: for each turn of the outer loop, the inner loop runs completely. This is how you build tables and grids.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(row * col + "\t");
}
System.out.println();
}Output:
1 2 3 4
2 4 6 8
3 6 9 12The inner loop's limit can depend on the outer variable, which is the trick behind triangle patterns:
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}Output:
*
**
***
****Quick check
break and continue
breakexits the loop immediately.continueskips the rest of the current repetition and goes on to the next.
// break: stop at the first number divisible by 7
for (int n = 20; n <= 40; n++) {
if (n % 7 == 0) {
System.out.println("First multiple of 7: " + n);
break;
}
}
// continue: print only odd numbers
for (int n = 1; n <= 9; n++) {
if (n % 2 == 0) {
continue;
}
System.out.print(n + " ");
}
System.out.println();Output:
First multiple of 7: 21
1 3 5 7 9In nested loops, break and continue affect only the innermost loop they're in.
Common mistakes
- Off-by-one errors:
i <= 10runs 10 times starting from 1, buti < 10runs 9 times. Trace the first and last values. - Infinite loops: forgetting to update the variable in a
while. - A semicolon after the header:
for (int i = 0; i < 5; i++);repeats an empty statement, and the block below runs once. - Using the loop variable after the loop: a variable declared in the
forheader doesn't exist outside it. - Forgetting the
;after thewhile (...)of a do-while.
Summary
for(init; condition; update) is for counting loops.whilechecks before each repetition and may run zero times;do-whilechecks after and always runs at least once.- Start an accumulator before the loop and update it inside.
- In nested loops, the inner loop runs fully for each outer repetition.
breakleaves a loop;continueskips to the next repetition.
Next lesson: arrays and methods: storing many values in one variable, and organizing code into reusable methods.