Java while Loop: Repeating Execution While Conditions Are Met, with Examples

In programming, we often need to repeatedly execute a block of code. For example, printing numbers from 1 to 10, calculating the sum from 1 to 100, etc. Java provides the while loop to fulfill this “repetitive execution” requirement. The core idea of a while loop is: “As long as the condition is met, the loop body will continue to execute until the condition is no longer met.”

1. Basic Syntax of While Loop

The structure of a while loop is very simple. Its basic format is as follows:

while (condition_expression) {
    // Loop body: Code to be executed when the condition is true
}
  • Condition Expression: Must be a boolean value (true or false). The loop body will only execute if the condition is true.
  • Loop Body: The code block that is repeatedly executed (if there is only one line of code, curly braces {} can be omitted, but it is recommended to always include them to avoid errors).

2. Why Use Loops?

Suppose we need to print the numbers from 1 to 5. Without a loop, we would have to write 5 lines of System.out.println():

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);

However, manually writing 1000 lines of code to print numbers from 1 to 1000 is obviously impractical. This is where the while loop becomes useful: it can automatically repeat execution with just a few lines of code.

3. Example 1: Print Numbers from 1 to 5

Requirement: Print the numbers from 1 to 5.
Idea:
1. Define a variable i and initialize it to 1 (represents the current number to print).
2. Use a while loop to check: as long as i is less than or equal to 5, execute the print operation.
3. Increment i by 1 after each print (otherwise, i will always be 1, making the condition always true and causing an infinite loop).

Code:

public class WhileExample {
    public static void main(String[] args) {
        int i = 1; // Initialize variable i starting from 1
        while (i <= 5) { // Condition: Is i less than or equal to 5?
            System.out.println(i); // Print the current value of i
            i++; // Increment i by 1 (critical! Otherwise, the condition will always be true, causing an infinite loop)
        }
    }
}

Output:

1
2
3
4
5

4. Example 2: Calculate the Sum from 1 to 10

Requirement: Calculate the sum of 1 + 2 + 3 + … + 10.
Idea:
1. Define a variable sum and initialize it to 0 (to accumulate the result).
2. Define a variable i and initialize it to 1 (start accumulating from 1).
3. Use a while loop: as long as i is less than or equal to 10, execute sum += i (add the current i to sum), then increment i by 1.

Code:

public class SumExample {
    public static void main(String[] args) {
        int sum = 0; // Initial sum is 0
        int i = 1; // Start accumulating from 1
        while (i <= 10) { // Condition: Is i less than or equal to 10?
            sum = sum + i; // Equivalent to sum += i
            i++; // Increment i by 1 to avoid infinite loop
        }
        System.out.println("The sum from 1 to 10 is: " + sum); // Output the result
    }
}

Output:

The sum from 1 to 10 is: 55

5. Note: Avoid Infinite Loops!

The most common mistake with while loops is infinite loops—the loop body executes indefinitely, causing the program to never terminate. The causes of infinite loops are usually:
1. Condition Expression Always True: For example, writing while (i <= 5) but forgetting to increment i, making the condition always true.
2. No Modification of the Condition Variable: For example, omitting i++, so i remains 1, and the condition is always true.

Example of an Infinite Loop (Incorrect):

int i = 1;
while (i <= 5) {
    System.out.println(i);
    // Error! i++ is forgotten, so i always remains 1, and the condition is always true
}

Solution: Ensure the loop body contains logic to eventually make the condition expression false (e.g., i++).

6. Supplement: Do-While Loop (Extension)

If you need to execute the loop body at least once (e.g., verifying a user password, where the input must be processed before checking correctness), use a do-while loop. Its feature is: execute the loop body first, then check the condition.

Syntax:

do {
    // Loop body (executed at least once)
} while (condition_expression);

Example:

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5); // The loop body executes first, then the condition is checked

Output: 1, 2, 3, 4, 5 (same result as the while loop, but with different logic).

7. Summary

  • while loops are used to repeatedly execute code when a condition is met, with the core logic of “check first, then execute”.
  • Syntax: while (condition) { loop body }—always ensure the loop body modifies the condition to avoid infinite loops.
  • Key Scenarios: Printing sequences (e.g., 1 to 100), accumulating sums (e.g., 1 to 100), and repeating tasks (e.g., user input validation).

By practicing simple loop examples (e.g., printing 1 to 100 or calculating the sum from 1 to 100), you can master the use of while loops!

Xiaoye