← Back to Home

while Loop

The while loop in Java is a control flow statement used to execute a block of code repeatedly as long as a given condition remains true. It is best suited when the number of iterations is not known in advance. This loop is widely used in input-driven logic, polling, and condition-controlled execution.

What Is a while Loop?

  • Executes code while a condition is true
  • Condition is evaluated before each iteration
  • Loop may execute zero or more times

Basic Syntax

while (condition) {
    // code to execute
}
          

Simple Example

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
          

Output:

1
2
3
4
5
          

Execution Flow of while Loop

  1. Condition is evaluated
  2. If condition is true, loop body executes
  3. Loop variable is updated
  4. Control returns to condition check
  5. Loop stops when condition becomes false

while Loop with Decrement

int i = 5;
while (i > 0) {
    System.out.println(i);
    i--;
}
          

Infinite while Loop

while (true) {
    System.out.println("Infinite loop");
}
          

Use case: Server listeners, background processes (with break conditions).

while Loop with break

while (true) {
    if (conditionMet) {
        break;
    }
}
          

while Loop with continue

int i = 0;
while (i < 5) {
    i++;
    if (i == 3) {
        continue;
    }
    System.out.println(i);
}
          

Nested while Loop

int i = 1;
while (i <= 3) {
    int j = 1;
    while (j <= 2) {
        System.out.println(i + "," + j);
        j++;
    }
    i++;
}
          

Common Use Cases

  • Reading user input
  • Polling conditions
  • Iterating until a condition is met
  • File reading, network checks

while vs for Loop

Feature while for
Condition Check Before loop Before loop
Iterations Known Usually no Usually yes
Structure Simple Compact
Use Case Condition-based Count-based

Common Beginner Mistakes

  • Forgetting to update loop variable (infinite loop)
  • Using wrong condition
  • Confusing while with do-while
  • Overcomplicating loop logic

Interview-Ready Answers

Short Answer

The while loop executes a block of code repeatedly as long as the condition is true.

Detailed Answer

In Java, the while loop evaluates a condition before each iteration and executes the loop body only when the condition is true. It is best used when the number of iterations is not predetermined.

Key Takeaway

The while loop is ideal for condition-controlled execution. Correct management of the loop condition and updates is crucial to avoid infinite loops.