A loop is a control-flow statement that allows Java to execute the same block of code repeatedly based on a condition or by traversing elements.
Java's four commonly taught loops are:
1. for loop
2. while loop
3. do-while loop
4. enhanced for loop (for-each)
The most important distinction is how repetition is controlled.
Every traditional loop has these basic ideas:
Initialization
↓
Condition
↓
Loop Body
↓
Update
↓
Condition
↺
For example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}Here:
Initialization → int i = 1
Condition → i <= 5
Body → System.out.println(i)
Update → i++
If the condition becomes false, the loop terminates.
Without a loop:
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);With a loop:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}Instead of writing the same operation repeatedly, we describe how repetition should happen.
The for loop is generally used when the initialization, condition, and update can be expressed conveniently together, especially for count-controlled repetition.
for (initialization; condition; update) {
// body
}Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}Consider:
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}Execution:
Step 1:
int i = 1
Step 2:
i <= 3
1 <= 3 → true
Step 3:
print 1
Step 4:
i++
i becomes 2
Step 5:
2 <= 3 → true
Step 6:
print 2
Step 7:
i++
i becomes 3
Step 8:
3 <= 3 → true
Step 9:
print 3
Step 10:
i++
i becomes 4
Step 11:
4 <= 3 → false
Exit
Output:
1
2
3
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}This:
int i = 1runs only once.
The repeated part is:
condition → body → update
Yes.
for (int i = 1, j = 5; i <= 5; i++, j--) {
System.out.println(i + " " + j);
}Output:
1 5
2 4
3 3
4 2
5 1
Yes, syntactically.
For example:
int i = 1;
for (; i <= 5; i++) {
System.out.println(i);
}Initialization is outside the loop.
You can also write:
for (int i = 1; ; i++) {
System.out.println(i);
}This has no condition, so the condition is effectively always true.
for (;;) {
System.out.println("Hello");
}This is an infinite loop.
Equivalent idea:
while (true) {
System.out.println("Hello");
}A while loop repeatedly executes its body as long as its condition is true.
The condition is checked before each iteration.
while (condition) {
// body
}Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
} Start
↓
Initialization
↓
Condition
↙ ↘
true false
↓ ↓
Body Exit
↓
Update
↓
Condition
↺
Because the condition is checked before entering the body.
Example:
int i = 10;
while (i < 5) {
System.out.println(i);
}Output:
(no output)
Why?
10 < 5
↓
false
↓
body never executes
Therefore:
whileis an entry-controlled loop.
while (true) {
System.out.println("Hello");
}This keeps executing unless something causes termination.
A do-while loop executes its body first and checks the condition afterward.
do {
// body
} while (condition);int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);Output:
1
2
3
4
5
Look at:
int i = 10;
do {
System.out.println(i);
} while (i < 5);Output:
10
Even though:
10 < 5 → false
the body already executed.
Execution:
Start
↓
Body
↓
Condition
↓
false
↓
Exit
Therefore:
do-whileis an exit-controlled loop.
Compare:
while (condition) {
body
}Condition
↓
Body
do {
body
} while (condition);Body
↓
Condition
That's the fundamental difference.
The enhanced for loop is also called the:
for-each loop
It is primarily used to traverse arrays and many Java collections.
for (dataType variable : arrayOrCollection) {
// body
}int[] numbers = {10, 20, 30, 40, 50};
for (int n : numbers) {
System.out.println(n);
}Output:
10
20
30
40
50
Conceptually:
n = 10
n = 20
n = 30
n = 40
n = 50
In:
for (int n : numbers)read it approximately as:
"For each element in
numbers, assign that element ton."
So:
numbers = {10,20,30}
iteration 1 → n = 10
iteration 2 → n = 20
iteration 3 → n = 30
Suppose:
int[] a = {10, 20, 30};for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}for (int x : a) {
System.out.println(x);
}The enhanced form is shorter when you simply want to process each element.
Suppose you need the index:
0
1
2
3
A traditional for loop is often more suitable:
for (int i = 0; i < a.length; i++) {
System.out.println(i + " " + a[i]);
}Enhanced for gives you the element directly, not an explicit index variable.
Be careful.
int[] a = {10, 20, 30};
for (int x : a) {
x = x + 10;
}This does not change the array to:
20 30 40
The variable x receives the element value.
For primitive elements, changing x doesn't change the array element.
If you need to modify elements by index:
for (int i = 0; i < a.length; i++) {
a[i] = a[i] + 10;
}String[] names = {"Ravi", "Arun", "Priya"};
for (String name : names) {
System.out.println(name);
}Output:
Ravi
Arun
Priya
Example:
ArrayList<String> names = new ArrayList<>();
names.add("Ravi");
names.add("Arun");
names.add("Priya");
for (String name : names) {
System.out.println(name);
}It is widely used for traversing collections.
| Feature | for |
while |
do-while |
Enhanced for |
|---|---|---|---|---|
| Condition | Before body | Before body | After body | Traversal-based |
| Minimum executions | 0 | 0 | 1 | 0 if no elements |
| Initialization syntax | Usually in loop | Usually before loop | Usually before loop | Variable declaration in loop |
| Update | Usually in loop | Usually in body | Usually in body | Automatic traversal |
| Index available directly? | ✅ | ✅ | ✅ | ❌ |
| Best for | Count-controlled loops | Condition-controlled loops | At-least-once execution | Arrays/collections |
| Can be infinite? | ✅ | ✅ | ✅ | Not normally used for intentional infinite looping |
This is an important exam question.
Condition checked before body:
for
while
Condition
↓
Body
Condition checked after body:
do-while
Body
↓
Condition
It's a traversal construct rather than simply being classified by the same condition pattern.
A loop inside another loop is called a nested loop.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(i + " " + j);
}
}Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Think:
Outer loop
↓
Inner loop runs completely
↓
Outer loop updates
↓
Inner loop runs completely again
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 4; j++) {
System.out.println("*");
}
}Outer loop:
3 times
Inner loop:
4 times for each outer iteration
Total:
3 × 4 = 12
body executions.
break terminates the nearest enclosing loop.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}Output:
1
2
3
4
Flow:
i = 5
↓
break
↓
loop terminates
continue skips the remaining body of 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
At i == 3:
continue
↓
skip remaining body
↓
next iteration
break |
continue |
|---|---|
| Terminates the loop | Skips current iteration |
| Control goes outside the loop | Control proceeds toward next iteration |
| Loop ends | Loop continues |
Memory trick:
break → STOP
continue → SKIP
Java also supports labels.
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);
}
}break outer; terminates the loop associated with the outer label.
This is particularly useful when working with nested loops.
Java also allows:
continue outer;This skips to the next iteration of the labeled outer loop.
Example:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer;
}
System.out.println(i + " " + j);
}
}This is dangerous:
int i = 1;
while (i <= 5) {
System.out.println(i);
}i never changes.
Therefore:
i = 1
condition true
print
condition true
print
condition true
...
Infinite loop.
Correct:
while (i <= 5) {
System.out.println(i);
i++;
}Look:
while (i <= 5);
{
System.out.println(i);
}That semicolon terminates the while statement.
It can produce surprising behavior.
Similarly, don't accidentally write:
for (int i = 0; i < 5; i++);unless an empty loop is genuinely intended.
Correct:
do {
System.out.println("Hello");
} while (condition);The semicolon is required.
This is different from:
while (condition) {
}where the semicolon is not placed after the condition.
Consider:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}The i declared there has scope associated with the for statement/body.
So this is invalid after the loop:
System.out.println(i); // ❌If you need i afterward:
int i;
for (i = 1; i <= 5; i++) {
System.out.println(i);
}
System.out.println(i);Java permits:
for (int i = 0; i < 10; i++);The loop body is an empty statement.
This is legal Java, although often accidental.
for (int i = 1; i <= 5; i++) {
}Eventually:
condition → false
while (true) {
}There is no natural false condition.
It requires something such as break or another termination mechanism to leave the loop.
You know or can naturally express the iteration using a counter.
for (int i = 0; i < 10; i++)The continuation condition is the main focus.
while (userInput != 0)The operation must happen at least once.
do {
// show menu
} while (choice != 0);You simply need to process each element.
for (int x : numbers)Imagine a menu:
1. Add
2. Delete
3. Search
0. Exit
You want the menu to appear at least once.
int choice;
do {
System.out.println("1. Add");
System.out.println("2. Delete");
System.out.println("3. Search");
System.out.println("0. Exit");
// read choice
} while (choice != 0);This is a natural use of do-while.
int[] marks = {80, 75, 90, 85};
int total = 0;
for (int mark : marks) {
total += mark;
}
System.out.println(total);Output:
330
Here we don't need an index, so enhanced for is convenient.
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
System.out.println("Found at index " + i);
break;
}
}Output:
Found at index 2
A traditional for loop is useful because we need the index.
When deciding which loop to use, ask:
Do I have a counter-controlled repetition?
YES → for
Is the condition the main thing controlling repetition?
YES → while
Must the body execute at least once?
YES → do-while
Am I simply processing every element of an array/collection?
YES → enhanced for
Need repetition?
│
▼
┌────────────────────┐
│ What are you doing?│
└─────────┬──────────┘
│
┌───────────────┼─────────────────┐
│ │ │
▼ ▼ ▼
Count/control Condition-driven Traverse elements
│ │ │
▼ ▼ ▼
for while enhanced for
│
│
Must execute once?
│
YES
↓
do-while
for
↓
Initialization → Condition → Body → Update
↖__________↙
while
↓
Initialization → Condition → Body → Update
↖________↙
do-while
↓
Initialization → Body → Update → Condition
↖______↙
enhanced for
↓
Get next element → Body → Get next element → ...
The
forloop repeatedly executes a block of statements while its condition is true, with initialization, condition, and update typically specified in one statement.
The
whileloop repeatedly executes its body as long as its condition is true, with the condition checked before each iteration.
The
do-whileloop executes its body at least once and then repeatedly executes it while its condition remains true.
The enhanced
forloop, or for-each loop, provides a convenient way to traverse elements of arrays and supported collections without explicitly managing an index.
| Doubt | Answer |
|---|---|
for can execute zero times? |
✅ |
while can execute zero times? |
✅ |
do-while can execute zero times? |
❌ |
do-while executes at least once? |
✅ |
for condition is checked before body? |
✅ |
while condition is checked before body? |
✅ |
do-while condition is checked after body? |
✅ |
Enhanced for works with arrays? |
✅ |
Enhanced for is also called for-each? |
✅ |
break terminates the loop? |
✅ |
continue skips the current iteration? |
✅ |
| Loops can be nested? | ✅ |
for= count,while= check then execute,do-while= execute then check, enhancedfor= visit every element.