While Loop
The while loop is Java's most fundamental loop statement.It repeats the statement or block of code while its controlling expression is true.In while loop, condition is given before the statement. It can execute the statements 0 or more times.
Syntax of the while loop:
while(condition) { //statements }
The condition can be 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.
If loop have only one statement then , curly braces are not necessary.
Flow Chart of the while loop:
Simple program of the while loop:
public class Test { public static void main(String[] args) { int i=5; while(i>0) { System.out.println("Count " + i ); i--; } } }
Count 5 Count 4 Count 3 Count 2 Count 1
Some important points about while loop:
1.Since the while loop evaluates its conditional expression at the beginning the loop , the body of the loop will not execute if condition is false at the beginning.
public class Test { public static void main(String[] args) { int i=5 , j=10; while(i>j) { System.out.println("While loop body"); } System.out.println("Out of While loop"); } }
OUTPUT
Out of While loop
2. The body of the while loop can be empty.This is because a null statement is syntactically valid in java.
public class Test { public static void main(String[] args) { int i=5 , j=10; while(++i<--j) System.out.println(i); } }
OUTPUT
8
3.If condition will always true then it will become infinite loop.
while(true) //infinite loop
0 comments :
Post a Comment