Java - While Loop


Java - While Loop

  • Repetitively executes set of statements till the given condition is satisfied.
  • Condition should result in Boolean type.
  • The set of statements are executed once before testing for the condition in do-while, but not the same in while loop.

Syntax - While:

while (expression) 
{
    \\ set of statement(s)
}

Sample Code:

public class JavaWhileLoop
{   
    public static void main(String [] args)
    {
        System.out.println("\n\n WikiTechy - Using While Loop\n");    
        int i = 10;
        while (i < 20)
        {
            System.out.println("i = " + i);
            i++;
        }
    }   
}

Code Explanation:



    Initialization of integer variable i is done via the code int i = 10;
    While loop with a condition on variable i is defined as 
while (i < 20)
{
    System.out.println("i = " + i);
    i++;
}

Output:



  • Hence the given while loop condition the code has been executed successfully.