While loop in java

The while loop is Java 's most fundamental loop statement. It repeats a statement or block while its controlling expression(condition) is true.


Syntax of while loop

  Flow Chart of While loop:

Syntax:

    while(condition/expression){  
    //code to be executed  
    }  
// result of expression must be of boolean type

Example of While loop

Note : we can use any expression in while loop which returns boolean type value.

  
  public class Example{  
    public static void main(String[] args) {  
        int i=1;  
        while(i<=10){  
            System.out.println(i);  
        i++;  
        }  
    }  
    }  
1
2
3
4
5
6
7
8
9
10

Example of while loop which prints table of 2


// example of while loop which  prints table of 2.
class Example
{
    public static void main(String[] args)
    {
        int i=1;
        while(i<=10)
        {
            System.out.println(2+" * "+i +" = "+(2*i));
            i++; //incrementing i
        }

    }
}
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Example of infinite while loop.


// example of infinite while loop.
class Example
{
    public static void main(String[] args)
    {        
        while(true)
        {
            System.out.println("Testing");
        }
    }
}
Testing
Testing
Testing
Testing
Testing
Ctrl + C