on Leave a Comment

Java while Loop with Examples

Java while loop executes multiple statements repeatedly until certain conditions holds true.

General form of Java while loop:

initialization;
while(condition)
{
  //Body of loop
}

The condition is evaluated and if the condition is true, body of loop is executed. Control is transferred back to the loop condition after executing the body of loop and the condition is evaluated again and if the condition is true, body of loop is executed.

Body of loop may contain zero or more statements. If there is only statement, then it is not necessary to put braces.

Flow Diagram of Java while Loop
Java while loop
Java while loop
Example of Java while Loop

class JavaWhileLoop
{
 public static void main(String[] args) {
  char c = 'A';

  while(c<='E')
  {
   System.out.println(c);
   c++;
  }
 }
}

Output:

A
B
C
D
E

0 comments:

Post a Comment