Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Infinite Loops
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
As discussed previously, it is essential to make sure each loop you write has a distinct end. For example, if the condition inside the for or while loop is always true, the loop will run forever, creating an infinite loop. It is possible to accidentally create a loop that never ends. Look below to see how the if statement prevents the infinite loop from executing over 10 times.
InfiniteLoopExample.java
package exlcode;
public class InfiniteLoopExample {
public static boolean exampleVariableOne = true;
public static int exampleVariableTwo = 0;
public static int counter = 0;
public static void main(String[] args) {
// without the if statement, the loop will be executed infinitely
// because exampleVariableOne is always true
while (exampleVariableOne) {
System.out.print(exampleVariableTwo + " ");
exampleVariableTwo++;
// the if statement ensures that the infinite loop
// is terminated after it runs 10 times
if (exampleVariableTwo > 10) {
exampleVariableOne = false;
}
}
}
}
If the if statement was not in the code, the while loop would run indefinitely. This is because the boolean expression inside the parenthesis always return "true". For this reason, we must ensure that our boolean expressions have an end by making sure they return as "false" in order to end the loop.
Infinite loops can cause your computer/browser/application to pause due to the continuous executions of the program, or even crash. One way to debug infinite loops is to print out the loop control variable after running the statements inside the loop to check what the cause of the infinite loop is.