Loops
Loops
A school program needs reliable data and clear rules. A loop repeats instructions while a rule permits it. Printing three roll numbers needs a starting value, a continuation condition and a way to reach the end.
Understand
A loop repeats instructions while a rule permits it.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
A loop that never changes the state used by its condition may never finish. Check the first and last intended iterations.
Introduction to Loops in Java
Imagine writing a task 100 times manually. Sounds exhausting, right? Loops in Java are designed to help you automate repetitive actions with control. In this tutorial, we’ll walk through all types of Java loops, when to use them, and how to write and understand their outputs step-by-step.
Types of Loops in Java
Java offers three primary looping constructs:
forloopwhileloopdo-whileloop
Let’s explore each with real-life examples and logic breakdowns.
Java for Loop
The for loop is best when you know how many times you want to repeat a block of code. It’s concise and powerful.
The for loop in the following example runs 5 times, printing a friendly message each time with the count.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Hello Java " + i);
}
}
}
Hello Java 1
Hello Java 2
Hello Java 3
Hello Java 4
Hello Java 5
Java while Loop
Use a while loop when you want the loop to run as long as a condition remains true — but you may not know in advance how many times.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
System.out.println("Counter: " + i);
i++;
}
}
}
Counter: 1
Counter: 2
Counter: 3
Explanation
The loop continues as long as i <= 3. Notice how you must manually initialize and increment i — this gives you more control but requires careful handling to avoid infinite loops.
Java do-while Loop
A do-while loop guarantees that the block runs at least once — even if the condition is false initially.
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Do-While Count: " + i);
i++;
} while (i <= 2);
}
}
Do-While Count: 1
Do-While Count: 2
Explanation
Unlike the while loop, this format ensures the loop body executes at least once before checking the condition.
Infinite Loops
An infinite loop is a loop that keeps running forever because it has no condition to stop. This can happen by accident (a bug), or on purpose — for example, programs that wait for user input or servers that always listen for requests often use infinite loops.
In the code below, the condition true always stays true, so the loop never ends. Be careful with infinite loops — they can crash or freeze your program if not used correctly.
public class InfiniteLoopExample {
public static void main(String[] args) {
// WARNING: This is an infinite loop
while (true) {
System.out.println("Running endlessly...");
}
}
}
Be cautious! Infinite loops can freeze your program if not intentionally used.
Break and Continue
Java loops can be further controlled using break and continue statements.
Using break
The break statement is used to stop a loop early. When the program reaches a break, it immediately exits the loop, even if the loop condition is still true.
In this example, the loop is supposed to run from 1 to 5. But when i becomes 3, the break statement is triggered, and the loop stops. So only 1 and 2 are printed.
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
}
}
1
2
Using continue
The continue statement is used inside loops to skip the rest of the current loop iteration and move to the next one. It is helpful when you want to ignore specific values or conditions during looping.
In this example, we use a for loop to print numbers from 1 to 5. When i equals 3, the continue statement is triggered, so the number 3 is skipped and not printed.
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
}
}
1
2
4
5
break exits the loop early; continue skips the current iteration and moves to the next.
Nested Loops
A nested loop means placing one loop inside another. The inner loop runs completely every time the outer loop runs once. This is useful when you're working with things like tables, grids, or repeating patterns in multiple dimensions (e.g., rows and columns).
In the example below, the outer loop runs 3 times (for i = 1 to 3), and for each value of i, the inner loop runs 2 times (for j = 1 to 2). This results in a total of 6 lines printed.
public class NestedLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
When to Use Which Loop?
| Loop Type | Best For |
|---|---|
for | Known number of repetitions |
while | Unknown repetitions, condition-controlled |
do-while | Always execute at least once |
Important boundaries and mistakes
A loop that never changes the state used by its condition may never finish. Check the first and last intended iterations.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: A loop that never changes the state used by its condition may never finish.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
for (int roll = 1; roll <= 3; roll++) {
System.out.println(roll);
}
}
}
Now change one thing: Change the upper bound to 2. Predict the new behavior before checking the worked variation.
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
for (int roll = 1; roll <= 3; roll++) {
System.out.println(roll);
}
}
}
Expected output
1
2
3A loop repeats instructions while a rule permits it. Printing three roll numbers needs a starting value, a continuation condition and a way to reach the end.
A loop that never changes the state used by its condition may never finish. Check the first and last intended iterations.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Worked variation: Change the upper bound to 2. The loop prints 1 and 2.
Check your understanding
What to remember
A loop repeats instructions while a rule permits it. Printing three roll numbers needs a starting value, a continuation condition and a way to reach the end. A loop that never changes the state used by its condition may never finish. Check the first and last intended iterations.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.