Infinite Loops

Naveen AnamaneniUpdated · 5 min read

A ceiling fan runs until you switch it off; nobody wants it to stop after ten turns. Some programs are like that on purpose: a web server answers requests until it's shut down. Most of the time, though, a loop that never ends is a bug, and your program just hangs. This lesson shows the three usual causes, how to stop a stuck program, and how to write an endless loop safely when you really want one.

Stopping a Stuck Program

If your program prints nothing (or the same thing forever) and never finishes:

  • In a terminal, press Ctrl + C.
  • In an IDE, click the red Stop button.

Then look for one of the causes below. The debugger ("Using the Debugger") is the fastest way to see which variable isn't changing.

Cause 1: The Variable Never Changes

Forgot.java
int saved = 0;
while (saved < 1000) {
    System.out.println("Saving...");
    // forgot: saved += 150;
}

saved stays 0, so saved < 1000 is true forever. Every loop body must move the condition towards false.

Cause 2: The Update Goes the Wrong Way

WrongWay.java
for (int i = 10; i > 0; i++) {
    System.out.println(i);
}

i starts at 10 and increases, so i > 0 stays true for a very long time: about 2.1 billion rounds, until i overflows to a negative number. It should be i--.

Cause 3: A Stray Semicolon

Semicolon.java
int n = 5;
while (n > 0);
{
    n--;
}

The ; after the condition is the loop body: an empty statement that never changes n. The block below it isn't part of the loop at all, and is never reached.

On Purpose: while (true) with break

Sometimes the cleanest loop has no condition in the header; it ends from inside, with break, when a certain input arrives:

Kiosk.java▶ Try it
import java.util.Scanner;
 
public class Kiosk {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = 0;
        while (true) {
            String city = sc.nextLine();
            if (city.equals("exit")) {
                break;
            }
            count++;
            System.out.println("Ticket " + count + " to " + city);
        }
        System.out.println("Kiosk closed after " + count + " tickets");
    }
}
Output
Ticket 1 to Pune
Ticket 2 to Mysuru
Kiosk closed after 2 tickets

How it works

  1. Line 7: while (true) would run forever on its own.
  2. Lines 9 to 11: when the user types exit, break leaves the loop.
  3. Line 15 runs after the loop, so we know the program got out.

Try it yourself: remove the break and type exit. What happens? Stop it with Ctrl + C.

for (;;) means the same as while (true); you'll see both in real code.

The Compiler Notices Some Mistakes

The compiler can see that code after an endless while (true) with no break can never run, and refuses it:

Compiler output
Unreach.java:5: error: unreachable statement
            System.out.println("never");
            ^

It can't spot the three causes above, though, because they depend on values at runtime.

Common Mistakes

Testing with == on decimals. for (double x = 0; x != 1.0; x += 0.1) never hits exactly 1.0 (see "Integer Overflow and Floating-Point Precision"), so it runs forever. Use < instead.

Reading input that never arrives. A loop waiting for exit hangs if input ends first. Check sc.hasNextLine() in programs that read from files.

Printing inside an endless loop. It floods the terminal and hides the real problem. Stop the program and use the debugger instead.

Practice

  1. Easy: Each of the three broken examples above has one bug. Fix each one so the loop ends.
  2. Harder: Write a while (true) loop that keeps doubling a number starting from 1 and stops with break as soon as it passes 1,000. Print how many doublings it took.

Quick check: Infinite loops

4 questions
1How do you stop a stuck program in a terminal?
2What's wrong with while (n > 0); followed by a block that does n--?
3How does a while (true) loop normally end?
4Why can for (double x = 0; x != 1.0; x += 0.1) run forever?

Key Takeaways

Was this tutorial helpful?

Lesson 62 of 482