Loops in Java
Loops are one of the most important concepts in Java. They allow us to execute a block of code repeatedly until a specific condition becomes false. Instead of writing the same code multiple times, loops help make programs shorter, cleaner, and more efficient.
In Java, there are three main types of loops:
forloopwhileloopdo-whileloop
Let's understand each of them with syntax and examples.
What is a Loop?
A loop is a control flow statement that repeatedly executes a block of code as long as a given condition is true.
Why do we use loops?
Reduce code duplication
Automate repetitive tasks
Improve code readability
Save development time
1. for Loop
Definition
The for loop is used when you know in advance how many times the loop should execute.
Syntax
for(initialization; condition; increment/decrement) {
// Code to execute
}
Flow
Initialization executes once.
Condition is checked.
If true, the loop body executes.
Increment/Decrement executes.
Steps 2–4 repeat until the condition becomes false.
Example 1: Print Numbers from 1 to 5
public class ForLoopExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
Example 2: Print Even Numbers
public class EvenNumbers {
public static void main(String[] args) {
for(int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
}
}
Output
2
4
6
8
10
Example 3: Reverse Order
public class ReverseLoop {
public static void main(String[] args) {
for(int i = 5; i >= 1; i--) {
System.out.println(i);
}
}
}
Output
5
4
3
2
1
2. while Loop
Definition
A while loop executes as long as the specified condition is true.
It is useful when the number of iterations is not known beforehand.
Syntax
while(condition) {
// Code to execute
}
Flow
Condition is checked.
If true, the loop body executes.
Condition is checked again.
The process repeats until the condition becomes false.
Example 1: Print Numbers from 1 to 5
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
}
}
Output
1
2
3
4
5
Example 2: Sum of Numbers
public class SumExample {
public static void main(String[] args) {
int i = 1;
int sum = 0;
while(i <= 5) {
sum += i;
i++;
}
System.out.println("Sum = " + sum);
}
}
Output
Sum = 15
3. do-while Loop
Definition
The do-while loop executes the loop body at least once, even if the condition is false.
This is because the condition is checked after executing the statements.
Syntax
do {
// Code to execute
} while(condition);
Example 1: Print Numbers
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while(i <= 5);
}
}
Output
1
2
3
4
5
Example 2: Executes Once Even When Condition is False
public class DoWhileDemo {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("Executed");
} while(i < 5);
}
}
Output
Executed
Explanation: Even though i < 5 is false, the loop executes once because the condition is checked after the loop body.
Difference Between for, while, and do-while
| Feature | for | while | do-while |
|---|---|---|---|
| Condition Checked | Before execution | Before execution | After execution |
| Executes at least once? | No | No | Yes |
| Best Use Case | Known number of iterations | Unknown number of iterations | Must execute at least once |
| Initialization | Inside loop | Outside loop | Outside loop |
| Increment/Decrement | Inside loop | Inside loop body | Inside loop body |
When Should You Use Each Loop?
Use for Loop
Printing numbers
Traversing arrays
Fixed number of iterations
Pattern programs
Example:
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
Use while Loop
Reading user input
Waiting for a condition
Unknown number of repetitions
Example:
while(passwordIncorrect) {
// Ask user again
}
Use do-while Loop
Menu-driven programs
Games
ATM applications
User input that must run at least once
Example:
do {
// Display menu
} while(choice != 0);
Common Mistakes
1. Forgetting Increment
int i = 1;
while(i <= 5) {
System.out.println(i);
}
This creates an infinite loop because i never changes.
2. Wrong Condition
for(int i = 1; i >= 5; i++) {
System.out.println(i);
}
The loop never executes because the condition is false initially.
3. Semicolon After Loop
for(int i = 1; i <= 5; i++);
{
System.out.println("Hello");
}
The semicolon ends the loop immediately, so "Hello" prints only once after the loop finishes.
Real-World Examples
| Scenario | Recommended Loop |
|---|---|
| Print 1 to 100 | for |
| Traverse an array | for |
| Read user input until valid | while |
| ATM Menu | do-while |
| Game Menu | do-while |
| Retry Login | while |
Summary
Loops are essential in Java programming because they help automate repetitive tasks and reduce code duplication.
Use a
forloop when the number of iterations is known.Use a
whileloop when the number of iterations is unknown.Use a
do-whileloop when the loop body must execute at least once.
Choosing the right loop improves code readability, maintainability, and overall program efficiency.
Conclusion
Understanding for, while, and do-while loops is a fundamental step toward mastering Java programming. Practice writing simple programs using each loop type, experiment with different conditions, and identify which loop best fits each scenario. As you build more applications, selecting the appropriate loop will become second nature and help you write cleaner, more efficient code.
we will see in the next article topic




