Skip to main content

Java: While Loop

A while loop is yet another control flow statement to loop a block of code until the condition gets satisfied.

  • The initialized variable is varied through a boolean condition and asked for it to increment or decrement based upon the need.
  • It is a sort of repeating if statement.

While loop checks for the condition whether it is true and proceeds to enter into the block of its body and does the necessary said conditions until the loop gets false and the block of code which is operating within exits out of the loop thus ending the operation after the said condition reaches its satisfaction limit.

Syntax

while(Boolean Condition)
{
    variable++ or -- //based on need
}

Example

public class Test
{
    public static void main(String[] args)
    {
        int token = 100;

        while(token < 110)
        {
            System.out.println("Token " +token+ " Not Yet Expired!");
            token++;
        }
    }
}

Output:

Token 100 Not Yet Expired!
Token 101 Not Yet Expired!
Token 102 Not Yet Expired!
Token 103 Not Yet Expired!
Token 104 Not Yet Expired!
Token 105 Not Yet Expired!
Token 106 Not Yet Expired!
Token 107 Not Yet Expired!
Token 108 Not Yet Expired!
Token 109 Not Yet Expired!

Here we have used a boolean condition of when the token number is less than 110 that is when the loop iteration reaches the point of the number 109 and checks for the number after that which is 110 which is as per condition false. It exits out the loop and proceeds to the other part of the code after the while loop.

Tags
Submitted by arilio666 on October 26, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.