While Loop in Java

While Loop in Java

While Loop In Java Notes

The while loop in Java runs as long as the given condition is true. while loop is an entry-controlled loop. That means decision whether the loop will run or not is taken at the beginning of the loop.

A while loop has three parts:

  • Initialization Expession
  • Test/Conditional Expression
  • Update Expression

alt text

The variable used in the initialization parts of a while loop is known as a loop variable. In the following example, n is the loop variable.

  int n=123,a;



      System.out.print(a+" ");


The while loop is used synonymously with for loop except in situations where a while loop is most apt for use.

Basically in situations where we are not sure how many times the loop should run, that is, there is no fixed limit. As you grow in stature in the programming world, the difference between the two loops will come quite naturally to you.

Following is a simple program to print the sum of digits of a number.

class DigitsOfNumber{

  public static void main(String args[]){

       int a, n=123, s=0;





        }//end of loop

    System.out.print("Sum = "+s);

 }//end of main

}//end of class