Infinite Loop in Java
An infinite loop is a loop that never ends. It keeps running again and again because the condition always stays true or no condition is written at all.
1. while(true) Loop
while (true) {
System.out.println("This is an infinite loop");
}
Explanation:
- This loop runs forever because true is always true.
2. for(;;) Loop
for (;;) {
System.out.println("This is an infinite loop");
}
Explanation:
- Here, nothing is written in the loop condition, so it keeps running endlessly.
3. do-while Loop
do {
System.out.println("This is an infinite loop");
} while (true);
Explanation:
- It runs the code first and then checks the condition.
- Since the condition is always true, it never stops.
4. for-each Loop (Note)
The for-each loop is not used for infinite loops.
It automatically stops after going through all items in a list or array.
for (String item : list) {
System.out.println(item);
}
Note:
- Be careful with infinite loops. They can hang or crash your program if not handled properly.
- Always use a break inside if you want to stop it based on some condition.
Summary:
- Infinite loop runs continuously and never stops on its own.
- Common ways to create it are: while(true), for(;;), and do-while(true).
- for-each loop is not used for infinite looping — it stops after going through all items.
- Use infinite loops carefully, and add a break if you want a way to exit.