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.

5 thoughts on “Watch for infinite loop

  1. Wow!!! I never thought such a small mistake can lead to big disaster. Thanks for the explaination. – Paul

Leave a Reply

Your email address will not be published. Required fields are marked *