Loops in Java
Learn how loops allow Java programs to execute a block of code repeatedly while a condition is satisfied.
What is a Loop?
A loop is a control-flow construct that repeats a block of statements. Loops are useful when the same operation needs to be performed multiple times.
Start
↓
Check condition
↓
Execute statements
↓
Update
↓
Check condition again
↓
Stop when condition is false
Types of Loops
| Loop | Use Case |
|---|---|
for |
Best when the number of iterations is known or controlled by an initialization, condition, and update. |
while |
Useful when repetition depends on a condition checked before each iteration. |
do-while |
Useful when the body must execute at least once. |
Enhanced for |
Convenient for iterating through arrays and collections. |
1. for Loop
The for loop combines initialization, a
condition, and an update expression in one loop header.
for (initialization; condition; update) {
// statements
}
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
for Loop Output
1
2
3
4
5
How a for Loop Works
- Initialization executes once.
- The condition is evaluated.
- If the condition is true, the loop body executes.
- The update expression executes.
- The condition is checked again.
2. while Loop
A while loop checks its condition before each
iteration. If the condition is initially false, the body
does not execute.
while (condition) {
// statements
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
3. do-while Loop
A do-while loop executes its body first and
checks the condition afterward. Therefore, the body executes
at least once.
do {
// statements
} while (condition);
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
do-while Executes at Least Once
int number = 10;
do {
System.out.println("Executed");
} while (number < 5);
Even though number < 5 is false, the message
is printed once because the condition is checked after the
body.
4. Enhanced for Loop
The enhanced for loop, also called the
for-each loop, provides a simple way to iterate through
arrays and other Iterable objects.
int[] numbers = {10, 20, 30, 40};
for (int number : numbers) {
System.out.println(number);
}
Enhanced for with Strings
String[] names = {
"Java",
"Python",
"C#"
};
for (String name : names) {
System.out.println(name);
}
5. Nested Loops
A loop inside another loop is called a nested loop. Nested loops are commonly used for tables, matrices, and pattern-based problems.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(i + " " + j);
}
}
6. break Statement
The break statement immediately terminates the
nearest enclosing loop or switch statement.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
7. continue Statement
The continue statement skips the remaining
statements in the current iteration and proceeds to the
next iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
Labeled break
Java supports labeled statements that can be used with
break to terminate an enclosing labeled loop.
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer;
}
System.out.println(i + " " + j);
}
}
Infinite Loops
An infinite loop continues indefinitely because its condition never becomes false.
while (true) {
System.out.println("Running...");
}
Loop with a Condition
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
Output:
Sum = 55
for vs while vs do-while
| Loop | Condition Checked | Minimum Executions | Best Used When |
|---|---|---|---|
for
|
Before each iteration | 0 | Iteration structure is known. |
while
|
Before each iteration | 0 | Repetition depends on a condition. |
do-while
|
After each iteration | 1 | Body must execute at least once. |
Practical Example: Multiplication Table
int number = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(
number + " x " + i + " = " + (number * i)
);
}
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Loop Best Practices
- Make sure the loop condition can eventually become false unless an infinite loop is intentional.
- Keep loop bodies small and readable.
- Avoid unnecessary nested loops when a simpler algorithm is available.
- Use enhanced for loops when you only need each element and not its index.
-
Use
breakandcontinueonly when they improve readability. - Be careful when modifying a collection while iterating over it.
Summary
Java provides several loop constructs for repeated
execution. The main loops are for,
while, do-while, and the
enhanced for loop. The
break and continue statements
provide additional control over loop execution.