Does Java recognize infinite loops?

I’ll just quote the Java Language Specification, as it’s rather clear on this:

This section is devoted to a precise explanation of the word “reachable.” The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression with value true.
  • There is a reachable break statement that exits the while statement.

Every other statement S in a nonempty block that is not a switch block is reachable iff the statement preceding S can complete normally.

And then apply the above definitions to this:

If a method is declared to have a return type, then every return statement (§14.17) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1).

In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to “drop off the end of its body.”

Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:

class DizzyDean {
  int pitch() { throw new RuntimeException("90 mph?!"); }
}

Leave a Comment