While loop in Java

While loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. The syntax of a while loop in Java is as follows:

while (condition) {
    // code block to be executed

Here, the condition is a Boolean expression that is tested before each iteration of the loop. If the condition evaluates to 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.

Here's an example of a while loop in Java:

int i = 1;
while (i <= 5) {

In this example, the while loop executes the code block inside it as long as the value of i is less than or equal to 5. The code block simply prints the value of i to the console and increments the value of i by 1 in each iteration.

The output of the above code will be:


Note that if the condition in the while loop is initially false, the code block will never be executed. Additionally, if the condition never becomes false, the while loop will execute indefinitely, resulting in an infinite loop.