«Back to Home

Core Java

Topics

While Loop In Java

while loop
 
In a program, a single statement or a group of statements are to be executed repeatedly depending upon the certain test condition, while statement is used.
 
Syntax

while(test condition)
{
// body of the loop;
}
 
Let’s understand with the flowchart, given below.

65
 
Here, the test condition is an expression, which expresses that how many times loop run. Body of the loop is a single statement or group of statements, which is enclosed in the braces and they are repeatedly executed till the value of the test condition evaluates to true. The control jumps to the first statement, if condition initially itself is false, the body of the loop will never be executed. It is also called as an entry-control loop.
 
The execution of the body of the loop depends upon the value of the test condition. This is shown in the figure.
 
Let’s see an example, given below.
 
Code
  1. public class WhileLoopExm {  
  2.     public static void main(String[] args) {  
  3.         int n = 1;  
  4.         while (n <= 10) {  
  5.             System.out.println("while loop : " + n);  
  6.             n++;  
  7.         }  
  8.     }  
  9. }  
66

Output

67

Summary

Thus, we learnt, if a single statement or a group of statements are to be executed repeatedly depending upon the certain test condition, while statement is used and also learnt how to create a while loop program in Java.