Infinite Loops mistakes
- Mistake: Creating a loop that never terminates, usually due to an incorrect or missing loop condition.
- Solution: Always verify your loop conditions and ensure that there is a clear exit point. For example, if using a
whileloop, check that the condition will eventually become false.
🔁 What is an Infinite Loop?
An infinite loop is a loop that never stops executing because its termination condition is never met or is missing.
That means — once it starts, it keeps running forever (until the program is forcibly stopped).
⚠️ Common Mistakes That Cause Infinite Loops in Java
1️⃣ Wrong or Missing Update Statement
If you forget to update the loop variable, the condition never changes.
int i = 1;
while (i <= 5) {
System.out.println("Hello");
// i++; // ❌ Missing increment causes infinite loop
}
✅ Correct version:
int i = 1;
while (i <= 5) {
System.out.println("Hello");
i++; // ✅ Updates loop variable
}
2️⃣ Incorrect Condition
If you use the wrong logical operator or condition, the loop may never end.
int i = 1;
while (i != 5) { // ❌ If i keeps skipping 5, it never ends
System.out.println("i = " + i);
i += 2; // 1, 3, 5, 7... it will skip 5 → Infinite loop
}
✅ Correct version:
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i += 2;
}
3️⃣ Always True Condition
If the condition is always true, the loop never ends.
while (true) {
System.out.println("I will run forever!");
}
👉 Such loops are intentional sometimes (e.g., servers),
but for beginners, this is often a mistake.
4️⃣ Floating-Point Comparison Errors
When using floating-point numbers (float or double) as loop variables, precision errors can cause infinite loops.
for (double d = 0.1; d != 1.0; d += 0.1) {
System.out.println(d);
}
⚠️ d may never be exactly equal to 1.0 due to floating-point rounding.
✅ Better:
for (int i = 1; i < 10; i++) {
double d = i / 10.0;
System.out.println(d);
}
5️⃣ Using Wrong Operator in Condition
Mistaking = for == (assignment instead of comparison).
int a = 1;
while (a = 5) { // ❌ Error: using = instead of ==
System.out.println("Wrong!");
}
✅ Correct:
int a = 1;
while (a == 5) {
System.out.println("Correct!");
}
6️⃣ Logic Errors in For Loops
If the loop variable moves away from the condition instead of toward it.
for (int i = 10; i >= 1; i++) { // ❌ increasing i but checking for >=
System.out.println(i);
i++; // moves away from termination → infinite loop
}
✅ Correct:
for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
💡 How to Avoid Infinite Loops
✅ Always check:
-
Is the loop variable initialized properly?
-
Does it change inside the loop?
-
Will the condition eventually become false?
🧠 Example: Intentional Infinite Loop (Safe Exit)
Sometimes you may want an infinite loop that breaks with a condition:
while (true) {
int num = (int)(Math.random() * 10);
System.out.println("Number: " + num);
if (num == 5)
break; // ✅ Exit when condition is met
}