Home >Java >javaTutorial >While Loop
Java's while
Loop: A Detailed Explanation
The while
loop in Java provides a way to repeatedly execute a block of code as long as a specified condition remains true. Unlike the for
loop, which is ideal when the number of iterations is known beforehand, the while
loop is best suited for situations where the number of repetitions isn't predetermined. The initialization, increment, or decrement operations are handled outside the loop's structure.
The while
loop is categorized as an entry-controlled loop because the loop condition is evaluated before each iteration. If the condition evaluates to true
, the loop body executes; otherwise, the loop terminates, and the program continues with the statements following the loop.
Example: Generating Even Numbers
Let's illustrate with a Java program that prints the first ten even numbers:
<code class="language-java">public class EvenNumbers { public static void main(String[] args) { int i = 0; System.out.println("Printing the list of first 10 even numbers \n"); while (i < 20) { // Condition: i must be less than 20 (to generate 10 even numbers) System.out.println(i); i += 2; // Increment i by 2 in each iteration } } }</code>
Output:
<code>Printing the list of first 10 even numbers 0 2 4 6 8 10 12 14 16 18</code>
This program initializes i
to 0. The while
loop continues as long as i
is less than 20. Inside the loop, the current value of i
(an even number) is printed, and then i
is incremented by 2 to prepare for the next even number. The loop terminates when i
reaches 20.
The above is the detailed content of While Loop. For more information, please follow other related articles on the PHP Chinese website!