Skip to Content

While Loop Example

  1. /*
  2.   While loop Example
  3.   This Java Example shows how to use while loop to iterate in Java program.
  4. */
  5.  
  6. public class SimpleWhileLoopExample {
  7.  
  8.   public static void main(String[] args) {
  9.    
  10.     /*
  11.      * Syntax of while loop is
  12.      *
  13.      * while( <condition> )
  14.      *   <loop body>
  15.      *
  16.      * where <condition> is a boolean expression. Loop body is executed as long
  17.      * as condition is true.
  18.      *
  19.      * Loop body may contain more than one statments. In that case it should be
  20.      * enclosed in a block.
  21.      */
  22.      
  23.      int i = 0;
  24.      
  25.      while(i < 5)
  26.      {
  27.        System.out.println("i is : " + i);
  28.        i++;
  29.      }
  30.      
  31.      
  32.      /*
  33.       * The following code will create an infinite loop, since j < 5 will always
  34.       * evaluated to true
  35.       */
  36.      //int j = 0;
  37.      //while(j < 5)
  38.      //  System.out.println("j is : " + j);
  39.      
  40.      
  41.      
  42.   }
  43. }
  44.  
  45. /*
  46. Output would be
  47. i is : 0
  48. i is : 1
  49. i is : 2
  50. i is : 3
  51. i is : 4
  52. */