How to Create an Infinite Loop in Java: Syntax and Examples
In Java, you can create an infinite loop using
while(true) or for(;;). These loops run endlessly because their conditions never become false.Syntax
An infinite loop runs forever because its condition never ends. The two common ways to write infinite loops in Java are:
while(true): The conditiontruealways stays true, so the loop never stops.for(;;): This is a for loop without any start, stop, or update conditions, so it runs endlessly.
java
while(true) { // code to repeat forever } for(;;) { // code to repeat forever }
Example
This example shows an infinite loop using while(true) that prints a message repeatedly. You can stop it manually (like pressing Ctrl+C) because it never ends on its own.
java
public class InfiniteLoopExample { public static void main(String[] args) { while(true) { System.out.println("This loop will run forever!"); try { Thread.sleep(1000); // pause 1 second to slow output } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } }
Output
This loop will run forever!
This loop will run forever!
This loop will run forever!
... (repeats every second)
Common Pitfalls
Infinite loops can cause your program to freeze or use too much CPU if not handled carefully. Common mistakes include:
- Forgetting to add a
breakor exit condition when needed. - Not adding delays like
Thread.sleep(), which can make the loop run too fast and overload the system. - Using infinite loops unintentionally, causing your program to hang.
Always make sure you have a plan to stop or control infinite loops.
java
/* Wrong: Infinite loop without pause or exit */ while(true) { System.out.println("No pause, runs too fast!"); } /* Right: Add a pause to reduce CPU use */ while(true) { System.out.println("Runs with pause"); try { Thread.sleep(1000); // 1 second pause } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // exit loop if interrupted } }
Quick Reference
Remember these quick tips for infinite loops in Java:
- Use
while(true)orfor(;;)for endless repetition. - Include
breakstatements or conditions to exit loops when needed. - Add
Thread.sleep()to avoid high CPU usage. - Be careful to avoid accidental infinite loops that freeze your program.
Key Takeaways
Use
while(true) or for(;;) to create infinite loops in Java.Always plan how to exit or control infinite loops to avoid freezing your program.
Add pauses like
Thread.sleep() to reduce CPU load during infinite loops.Avoid accidental infinite loops by carefully checking loop conditions.
Infinite loops run endlessly because their conditions never become false.