Java Loops : for, while, do-while
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:
for
loopwhile
loopdo-while
loop
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 |
QUIZ
Question 1:What is the key distinction of a do-while
loop in Java compared to for
and while
?
Question 2:The for
loop in Java is best suited for situations where the number of iterations is known ahead of time.
Question 3:Which of the following behaviors correctly describe a while
loop in Java?
Question 4:What will be the output of the following code?
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
Comments
Loading comments...