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:

      1111296389.jpg

    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.

    Example)
    drag_handle
       
      public class Example{  
        public static void main(String[] args) {  
            int i=1;  
            while(i<=10){  
                System.out.println(i);  
            i++;  
            }  
        }  
        }  
    Output:
    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
            }
    
        }
    }

    Output:
    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");
            }
        }
    }

    Output:
    Testing
    Testing
    Testing
    Testing
    Testing
    Ctrl + C

What next?

The next topic is Do While loop in java

Share this page