Incremental Java
Infinite Loops

What is an Infinite Loop?

An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.
public void sillyLoop( int i )
{
   while ( i != 0 )
   {
      i-- ;
   }
}
If the value of i is negative, this goes (theoretically) into an infinite loop (in reality, it does stop, but due to a unusual technical reason called overflow. However, pretend it does go on forever).

This is a silly example, but it's common for infinite loops to accidentally occur. Most of the times, it's because the variables used in the condition are not being updated correctly, or because the looping condition is in error.

One way to detect the error is to print a message at the beginning of the loop, and print out the values of the variables that appear in the condition, just to see what's going on:

public void sillyLoop( int i )
{
   while ( x + y < z )
   {
      // Debugging below
      System.out.println( "[DEBUG] x = " + x + " y = " + y + " z = " + z ) ;

      // More code
   }
}
We print out x, y, and z since these variables appear in the condition. By inspecting how they change each iteration, we can get some insight into the possible errors in the loop.

Intentional Infinite Loops

There are times when you want to have an infinite loop, on purpose. Think of a web server. A typical web server takes a request (say, for a web page), returns a web page, and waits for the next request.

Here are some pseudocode for an infinite loop for a web server.

while ( true )
{
   // Read request
   // Process request
}
Another popular way is:
for ( ; ; )
{
   // Read request
   // Process request
}
I would prefer to see:
// loopforever is not a Java construct
loopforever
{
   // Read request
   // Process request
}
Only because it makes it easier to read.