Java while loop
Contents
While Loop statement in Java : Iterative Statement (Loop Control Statement)
- In java “while” is iteration statements like for and do-while.
- It is also called as “Loop Control Statement“.
- “While Statement” repeatedly executes the same set of instructions until a termination condition is met.
- While loop is Entry Controlled Loop because condition is check at the entrance.
- If initial condition is true then and then only control enters into the while loop body
- In for loop initialization,condition and increment all three statements are combined into the one statement , in “while loop” all these statements are written as separate statements.
- Conditional Expression written inside while must return boolean value.
Flow Diagram :
Syntax :
while(condition) { // body of loop }
- The condition is any Boolean expression.
- The body of the loop will be executed as long as the conditional expression is true.
- When condition becomes false, control passes to the next line of code immediately following the loop.
- The curly braces are unnecessary if only a single statement is being repeated.
Live Example :
class WhileDemo { public static void main(String[] args){ int cnt = 1; while (cnt < 11) { System.out.println("Number Count : " + cnt); count++; } } }
Legal Ways of Writing While loop :
While Loop : Single Statement Inside Loop Body
class WhileDemo { public static void main(String[] args){ int cnt = 1; while (cnt < 11) System.out.println("Number Count : " + cnt++); } }
Single Statement is a part of While Loop as there is no opening and closing curly braces.
Suppose we want to embed multiple statements as a part of while loop body then we can put all the statements in a block.
While Loop : Boolean Condition
class WhileDemo { public static void main(String[] args){ boolean b1 = true; while (b1) { System.out.println("Number Count : " + cnt); cnt++; if(cn==5) b1 = false; } } }
We can put single variable as while condition but it must be of type boolean. thus the following statement will cause compile time failure -
int b1 = 12; while (b1) { System.out.println("Number Count : " + cnt); cnt++; if(cn==5) b1 = 1; }
While Loop with no body
class NoBody { public static void main(String args[]) { int i, j; i = 10; j = 20; while(i < j); // no body in this loop { System.out.println("Out of the Loop"); } } }
*Note : Semicolon after while condition is perfectly legal.