Java While Loop

The while loop in Java repeatedly executes a block of code as long as a specified condition remains true. It's useful when the number of iterations is not known beforehand.

Key Topics

1. Syntax

The basic syntax of a while loop is as follows:

while (condition) {
    // Code to execute while condition is true
}

2. Example

Example of using a while loop:

public class WhileExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

3. Avoiding Infinite Loops

Ensure that the loop condition will eventually become false; otherwise, the loop will run indefinitely.

Example of an infinite loop:

public class InfiniteLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            // i++ is missing, leading to an infinite loop
        }
    }
}

Output:

Count: 1
Count: 1
Count: 1
// This will continue indefinitely

Key Takeaways

  • The while loop checks the condition before executing the loop body.
  • Useful when the number of iterations is not predetermined.
  • Be cautious to modify loop variables to prevent infinite loops.