Infinite Loop
Part of the Fundamentals section of Coddy's Java journey — lesson 49 of 73.
An infinite loop is a loop that never stops because its condition always evaluates to true. These loops can occur with any loop type (for, while, do-while), but they are most commonly associated with while and do-while loops because their conditions are explicitly stated.
Here's an example of an infinite while loop:
while (true) {
System.out.println("This will print forever!");
}In this case, the condition is simply true, which always evaluates to true. Thus, the loop will run indefinitely, printing the message over and over again.
Another way to create an infinite loop is by omitting the condition in a for loop:
for (;;) {
System.out.println("This also prints forever!");
}Here, the initialization, condition, and update parts of the for loop are all omitted. This creates a loop that runs forever.
Infinite loops can also occur unintentionally, such as when the loop's condition is always true due to a logic error:
int i = 0;
while (i < 10) {
System.out.println("i is: " + i);
// Missing i++ to increment i
}In this example, the variable i is never incremented, so the condition i < 10 is always true. This creates an infinite loop that will keep printing "i is: 0" indefinitely.
Infinite loops can be useful in some cases, such as in server programs that need to keep running until manually stopped. However, they can also cause programs to freeze or crash if not handled properly.
Cheat sheet
An infinite loop is a loop that never stops because its condition always evaluates to true.
Intentional infinite while loop:
while (true) {
System.out.println("This will print forever!");
}Intentional infinite for loop (omitting all parts):
for (;;) {
System.out.println("This also prints forever!");
}Unintentional infinite loop (missing increment):
int i = 0;
while (i < 10) {
System.out.println("i is: " + i);
// Missing i++ to increment i
}Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else