In Java, the while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a certain condition is true. The basic syntax of a while loop is as follows:
while (condition) { // code block to be executed while condition is true }
Here’s how it works:
- The condition is evaluated before each iteration of the loop.
- If the condition is true, the code block inside the loop is executed.
- After the code block is executed, the condition is evaluated again, and the loop continues as long as the condition is true.
- When the condition becomes false, the loop is terminated and control transfers to the next statement after the loop.
Here’s an example of using a while loop to print the numbers from 1 to 10:
int i = 1; while (i <= 10) { System.out.println("The value of i is " + i); i++; // increment i by 1 }
In this example, we declare a variable i
and initialize it to 1
. We then use a while loop to repeatedly print out the value of i
and increment it by 1
until i
becomes greater than 10
. The loop condition i <= 10
is checked at the beginning of each iteration, and if it is true
, the loop body is executed.
When you run this code, you will see the following output:
The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 The value of i is 5 The value of i is 6 The value of i is 7 The value of i is 8 The value of i is 9 The value of i is 10
As you can see, the loop runs 10 times, printing out the value of i
on each iteration. Once i
reaches 11
, the loop condition becomes false
and the loop terminates.