Loop mechanisms are useful for repeatedly executing blocks of code while a Boolean condition remains true.
Syntax of while loop
while (Boolean expression) { statement(s) //block of statements }
The while statement will evaluate the Boolean expression within the parentheses, and continue to execute the statement(s) within the curly braces as long as the expression is true.
While loop example
class WhileLoopExample { public static void main(String args[]){ int i=5 while(i>1){ System.out.println(i); i--; } } }
The output of this program is:
5
4
3
2
Getting Stuck in an Infinite Loop
class WhileLoopExample2 { public static void main(String args[]){ int i=10 while(i>1) { System.out.println(i); i++; } } }
This loop would never end, it’s an infinite while loop. This is because condition is i>1 which would always be true as we are incrementing the value of i inside while loop.
Here is another example of infinite while loop:
while (true){
statement(s);
}
Infinite loops are extremely dangerous and can cause many undesirable effects in the program.
Well said and perfect design principle.
Wow!!! I never thought such a small mistake can lead to big disaster. Thanks for the explaination. – Paul
I heard this is one of the test Space craft perform very seriously. Excellent explanation.
Actually scary a small mistake can cost you lot in critical mission.
Very Fundamental. I have bookmarked your web site. Please keep me informed about the new content if possible.