Tutorials

Java Loop Control


Infinite Loop in java


In general while working with loops like for, while or do-while if proper care is not taken then your code may enter an infinite loop.

 

You may also use the startegy that we are about to discuss purposefully in case you wish to make your code enter infinite loop.

 

Some of the common codes that will result in infinite loop are:

  • use of for(;;){//your code} in the code
  • use of while(true){//your code} in the code
  • use of do-while(true){//your code} in the code

 

Code can enter infinite loop if coder makes these common mistakes (see the below code snippet):

 

Example 1:


public class printNumber {

      public static void main(String[] args) {

            int i =1;

            while(i<10){

                  System.out.println("value of i="+ i);

            }

      }

}

OUTPUT:

value of i is printed infinite times (infinite loop)

 

Reason: Coder forgot to increment value of i. So its value always remains 1 and hence will evaluate to true. Thus the loop body will keep on executing for infinite times.

 

Example 2:


	
public class printNumber {

      public static void main(String[] args) {

            int i =1;

           do {

                  System.out.println("value of i="+ i);

            }while(i<10);

      }

}

OUTPUT:

value of i is printed infinite times (infinite loop)

 

Reason: Coder forgot to increment value of i. So its value always remains 1 and hence will evaluate to true. Thus the loop body will keep on executing for infinite times.

 

Mostly beginner tends to make these kind of mistakes. So if you are one note this down to save your code from entering into infinite loop unncessarily.



Please Share this page
Views : 97
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!