Branching Statements

Infinite Loops

🙋 Need help? Ask an expert now!

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.

Application Question

Which of the following is an example of an infinite loop?