Course contentsShow
← Java
Lesson 163 of 2,8704. Control Flow StructuresFree lesson

Infinite Loops: Intentional and Accidental

Recognize when infinite loops are intentional (e.g., server loops) vs bugs, and how to detect them.

Infinite Loops: Intentional and Accidental

What you'll learn: You'll discover that infinite loops aren't always bugs—sometimes they're exactly what you need, and you'll learn to tell the difference.

What Is an Infinite Loop?

An infinite loop is a loop whose condition never becomes false, causing it to run forever (or until externally stopped). This happens when you write while (true) or when a loop's condition accidentally never changes.

Intentional Infinite Loops

Some programs need to run continuously. Think of a server waiting for requests, a game's main loop, or a program monitoring sensors. These use infinite loops on purpose:

while (true) {
    // Server waiting for client connection
    // Check for input
    // Process request
}

Analogy: Like a store clerk who stays at the register all day waiting for customers—they don't leave after helping one person; they loop back to waiting.

Accidental Infinite Loops (Bugs)

More commonly, beginners create infinite loops by mistake. This happens when the loop condition never gets a chance to become false:

int count = 0;
while (count < 5) {
    System.out.println("Hello");
    // Oops! Forgot to increment count
}

This loop never ends because count stays 0 forever.

How to Detect Them

Warning signs:

  • Your program "hangs" and never finishes
  • No output appears or output repeats endlessly
  • The loop variable never changes inside the loop body
  • The condition doesn't depend on anything that changes

Quick fix when stuck: Most IDEs let you stop a running program (often a red square button), or press Ctrl+C in the terminal.

Key Takeaway: Infinite loops are intentional when you need continuous operation (like servers), but accidental when you forget to update loop control variables—always verify your condition will eventually become false unless you explicitly want while (true).