5 Minutes of Java (7. While loop)

While Loop Structure:

While (Conditional Test)
{
   Statements; //inside the loop block/body
}

Meaning:  While conditional test result is true, keep looping (statements inside the loop block/body will be executed/run)

Example:

int cupsOfRice = 0;
while(cupsOfRice<4)
{
 System.out.println("I am eating");
 cupsOfRice++; //cupOfRice = cupOfRice + 1;
}
System.out.println("I am full");

Output:

I am eating
I am eating
I am eating
I am eating
I am full

Common uses of While Loop:

  • When the number of iterations is not known from the outset.
  • When an infinite loop is enforced, until the condition becomes false.

Example:

int num = Helper.readInt("Enter a number between 1 to 10> ");
while (num < 1 || num > 10) {
   num = Helper.readInt("Invalid Numer, 1 to 10 please > ");
}
System.out.println("You entered " + num);

In this example, we are not sure how many times a user would enter a invalid number, so we use while loop. As long as the user enters a invalid number, the program will keep asking the user to enter a new number again.