The while Loop


The while Loop
The while loop loops through a block of code as long as a specified condition is true.

In the example, the code in the loop will run, over and over again, as long as a variable i is less than 5.
 int i = 0;
 while ( i < 5 ) {
   System.out.print( i );
   i++;
 }     // Output: 01234

The do...while Loop
The do...while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.

Do not forget to increase the variable used in the condition in the examples. Otherwise, the loop will never end!
 int i = 0;
 do
   System.out.println( i++ );
 while ( i < 5 );
 // Output: 01234

Factorial.java (calculating the factorial of a number, e.g., 5! = 2×3×4×5 =120)

 public class  Factorial {
   public static void  main( String[ ] args ) {
     // Convert the input number from a string to an integer.
     int number = Integer.parseInt( args[0] );
     int i = 1, factorial = 1;

     /* Loop from 2 to the input number and  *
      * multiply them to get the factorial.  */
     while (  <=  )
       factorial = factorial * i;
     System.out.println( number + "! = " + factorial );
   }
 }
shell> java Factorial