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

Writing Effective while Loop Conditions

Understand boolean expressions as loop conditions, common patterns, and avoiding infinite loops.

Writing Effective while Loop Conditions

You'll learn how to write boolean expressions that control while loops safely and effectively, including how to avoid infinite loops.

What Makes a Good Loop Condition?

A while loop continues executing as long as its condition evaluates to true. The condition is a boolean expression—something that produces either true or false. Writing effective conditions means ensuring your loop will:

  1. Eventually become false (preventing infinite loops)
  2. Clearly express the loop's purpose
  3. Be efficient and safe (using short-circuit evaluation when appropriate)

Common Patterns for Loop Conditions

Counting patterns:

int count = 0;
while (count < 10) {
    count++;
}

Sentinel value patterns:

int value = 5;
while (value != -1) {
    // Process value, then update it
    value--; // This will eventually reach -1
}

Compound conditions:

int x = 0;
int y = 10;
while (x < 5 && y > 0) {
    x++;
    y--;
}

Avoiding Infinite Loops

An infinite loop runs forever because its condition never becomes false. This typically happens when you forget to update the variables in the condition:

// DANGER: Infinite loop!
int count = 0;
while (count < 10) {
    // Missing: count++ or count--;
}

Always ensure that something inside the loop body changes the state that affects the condition.

Key Considerations

  • Use relational operators (<, >, <=, >=, ==, !=) appropriately
  • Combine conditions with logical operators (&&, ||) when needed
  • Leverage short-circuit evaluation for efficiency and safety
  • Make sure variables in the condition are modified inside the loop

Key Takeaway: An effective while loop condition must eventually evaluate to false by tracking variables that change inside the loop body—otherwise, you risk creating an infinite loop.