Looping Statements in Java (for, while, do-while, break, continue)
Introduction: Why Loops Are Important in Java
In programming, many tasks need to be repeated:
- Print numbers from 1 to 10
- Read multiple inputs
- Process a list of values
Instead of writing the same code again and again, Java uses loops.
Loops help programs repeat tasks automatically.
What Are Looping Statements?
Looping statements allow a block of code to execute repeatedly as long as a condition is true.
In simple words:
Loops save time and reduce code duplication.
Types of Looping Statements in Java
Java provides three main loops:
forloopwhileloopdo-whileloop
Additionally, Java provides:
breakcontinue
to control loop execution.
for Loop
What Is a for Loop?
The for loop is used when the number of repetitions is known in advance.
Syntax
for (initialization; condition; increment/decrement) {
// code to repeat
} Example
for (int i = 1; i <= 5; i++) {
System.out.println(i);
} Output:
2
3
4
5
Explanation
int i = 1→ start valuei <= 5→ conditioni++→ increase value
while Loop
What Is a while Loop?
The while loop checks the condition first, then executes the code.
Syntax
while (condition) {
// code to repeat
} Example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
} Explanation
- Condition is checked before execution
- Loop runs only if condition is true
do-while Loop
What Is a do-while Loop?
The do-while loop executes the code at least once, even if the condition is false.
Syntax
do {
// code to repeat
} while (condition); Example
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5); Key Difference
Code runs once before checking the condition.
Comparison of for, while, and do-while
| Loop Type | Condition Check | Use Case |
|---|---|---|
| for | Before execution | Known repetitions |
| while | Before execution | Unknown repetitions |
| do-while | After execution | At least one execution |
break Statement
What Is break?
The break statement stops the loop immediately.
Example
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
} Output:
2
3
4
continue Statement
What Is continue?
The continue statement skips the current iteration and moves to the next one.
Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
} Output:
2
4
5
Common Beginner Mistakes
- Infinite loops (missing increment)
- Wrong loop condition
- Forgetting semicolon in
do-while - Misusing
breakandcontinue
Frequently Asked Questions (FAQs)
Q1. Which loop is best for beginners?
The for loop is easiest to understand and commonly used.
Q2. Can loops run forever?
Yes, if the condition never becomes false.
Q3. Is do-while loop necessary?
Yes, when code must run at least once.
Q4. Can we use break outside a loop?
No. break works only inside loops or switch statements.
Q5. Can loops be nested?
Yes. One loop can be placed inside another loop.