Java - While Loop

The while loop is a control structure in Java that allows you to repeatedly execute a block of statements as long as a specified condition is true. The while loop is used to perform a repetitive task until the condition is false.

Syntax:

The basic syntax of the while loop in Java is as follows:

while(condition){
   //Statements to be executed repeatedly
}

The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the statements inside the loop are executed. If the condition is false, the loop terminates and control passes to the next statement after the loop.

Example:

Let's say we want to print the numbers from 1 to 5 using a while loop. We can do it as follows:

int i = 1;
while(i <= 5){
   System.out.println(i);
   i++;
}

Explanation:

In the above example, we initialize the variable 'i' with a value of 1. The condition inside the while loop checks if 'i' is less than or equal to 5. If the condition is true, the statements inside the while loop are executed. We print the value of 'i' using the System.out.println() method and increment the value of 'i' by 1 using the i++ statement. This process continues until the value of 'i' becomes greater than 5.

Infinite Loops:

If the condition specified in the while loop is always true, the loop will run indefinitely. Such a loop is called an infinite loop. For example:

while(true){
   //Statements to be executed repeatedly
}

This loop will never terminate unless the program is terminated forcefully.

Break and Continue Statements:

The break statement can be used to terminate a loop prematurely. The continue statement can be used to skip the rest of the statements in the current iteration of the loop and move to the next iteration.

Example:

Let's say we want to print the numbers from 1 to 10, but we want to skip the numbers 3 and 7. We can do it as follows:

int i = 1;
while(i <= 10){
   if(i == 3 || i == 7){
      i++;
      continue;
   }
   System.out.println(i);
   i++;
   if(i > 10){
      break;
   }
}

Explanation:

In the above example, we initialize the variable 'i' with a value of 1. The condition inside the while loop checks if 'i' is less than or equal to 10. If the condition is true, the statements inside the while loop are executed. Inside the loop, we check if 'i' is equal to 3 or 7. If it is, we skip the rest of the statements in the current iteration using the continue statement and move to the next iteration. If 'i' is not equal to 3 or 7, we print the value of 'i' using the System.out.println() method and increment the value of 'i' by 1 using the i++ statement. We also check if the value of 'i' is greater than 10. If it is, we terminate the loop using the break statement.