Site icon TestingDocs.com

Java program for while loop

Program Description

Write a java program to demonstrate a simple while loop. We use a while loop in a program when we know the exit condition and not sure how many times to loop the iterations.  The loop will be executed until the loop expression is true.

There is another variation of the loop called the do-while loop. Do-while will loop at-least once before evaluating the loop condition.

Syntax

while (expression)

{

        //statements(s)

}

 

Java Program

For example, we want to exit the loop when the count reaches 10.  Below is a simple Java program to make use of the while loop.

The while loop will be executed 10 times and the loop is exited when count reaches 11.

/***********************************************************
 * WhileLoop.java
 * @program : Java program for while loop
 * @web : www.testingdocs.com
 * @version : 1.0
 ************************************************************/ 

public class WhileLoopDemo {
  public static void main(String[] args)
  {
    int count=1;
    while(count<11)
    {
      System.out.println("Count is :" + count);
      count++;
    }
  }
}

Program Output

Count is :1
Count is :2
Count is :3
Count is :4
Count is :5
Count is :6
Count is :7
Count is :8
Count is :9
Count is :10

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

More information on Java can be found on the official website:

https://www.oracle.com/in/java/

Exit mobile version