Introduction to Java While Loop with Examples

Beantwortet mit GPT-4o-mini von Java Q&A Hub

Frage:

Introduce Java While Loop and give examples

Antwort:

A while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the condition evaluates to true. If the condition is false at the start, the code inside the loop will not execute at all.

Syntax of a While Loop

while (condition) {
    // Code to be executed
}

Key Points:

  • The condition is evaluated before the execution of the loop's body.
  • If the condition is true, the code inside the loop is executed.
  • After executing the loop's body, the condition is checked again.
  • If the condition becomes false, the loop terminates, and control passes to the statement following the loop.
  • It's important to ensure that the loop will eventually terminate; otherwise, it can lead to an infinite loop.

Example 1: Basic While Loop

Here’s a simple example that prints numbers from 1 to 5:

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1; // Initialize the counter
        while (i <= 5) { // Condition
            System.out.println(i); // Print the current value of i
            i++; // Increment the counter
        }
    }
}

Output:

1
2
3
4
5

Example 2: Using a While Loop to Sum Numbers

In this example, we will use a while loop to calculate the sum of numbers from 1 to 10.

public class SumWhileLoop {
    public static void main(String[] args) {
        int sum = 0; // Initialize sum
        int i = 1; // Initialize counter

        while (i <= 10) { // Condition
            sum += i; // Add i to sum
            i++; // Increment counter
        }

        System.out.println("The sum of numbers from 1 to 10 is: " + sum);
    }
}

Output:

The sum of numbers from 1 to 10 is: 55

Example 3: Infinite Loop (with a Break)

Here’s an example of an infinite loop that can be terminated using a break statement:

public class InfiniteLoopExample {
    public static void main(String[] args) {
        int count = 0;

        while (true) { // Infinite loop
            System.out.println("Count: " + count);
            count++;
            if (count >= 5) { // Condition to break the loop
                break; // Exit the loop
            }
        }
    }
}

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Conclusion

The while loop is a fundamental control structure in Java that allows for repeated execution of a block of code as long as a specified condition is true. It is essential to manage the loop's condition carefully to avoid infinite loops and ensure that the loop will eventually terminate.