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.
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.