Infinite Loop in Java

Infinite loop in java refers to a situation where a condition is setup so that your loop continues infinitely without a stop. A loop statement is used to iterate statements or expressions for a definite number of times but sometimes we may need to iterate not for a fixed number but infinitely. For such situations, we need infinite loops in java. There are basically three looping structures in java: for, while and do while.

These structures are used for iterations i.e., these  statements can allow the repetition of a set of statements or functions. While using them for infinite repetitions, we may use the following ways.

The syntax of a for loop goes like this:

Example:

It will print:

Hello World

Hello World

Now, if we want to make our for loop go infinitely, we can try the following ways:

This program will print “Hello World” infinitely since the condition “i>0” will always be true.

This is a rather an unintentional and tedious way of doing this. You would probably never want to do things like printing “Hello world” an infinite number of times. This would probably be a programming error. But using infinite loops can also be intentional according to the requirements of a program. An elegant way of writing infinite loops are given below.

Infinite Loop in Java

Using For

Using While

Using Do While

In the above code, the statements or expressions will be executed infinitely and there will be no confusion too.

But, one important thing has to be taken into consideration while writing infinite Loops.

An infinite loop must contain a break statement. An infinite loop must have an exit condition that has to be executed once the goal of the program has been met. For example, you may want to write a program in which the computer guesses a number from 1 to 10 and the user also is asked to guess a number from 1 to 10, and the program only exits when the user’s guess matches that of the  computer’s.

We usually use:

while(true) {

}

Since it is more readable and clear way of generating code as it clarifies to the reader that  the code has been intended to be an infinite loop. Also, the break condition is very necessary when we want to come out and should be thought and implemented as per the program requirements.

Leave a Reply

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