Unreachable statement compile error in Java

UnderDog picture UnderDog · Aug 19, 2013 · Viewed 74.3k times · Source
class For1
{
  public static void main(String args[])
  {
    int a = 0;
    for(;;)
    {
      break;
      System.out.println(a); //Line 1
      ++a;//Line 2
    }
  }
}

I know that Line 1/Line 2 will never be executed. But still I don't understand why a compile time error is thrown. I am getting "unreachable statement" compile error.

Does it mean that compiler checks whether it is able to compile for all branches/lines of code ?

Answer

Jon Skeet picture Jon Skeet · Aug 19, 2013

Does it mean that compiler checks whether it is able to compile for all branches/lines of code ?

It means the compiler checks that every statement is reachable.

From section 14.21 of the JLS:

It is a compile-time error if a statement cannot be executed because it is unreachable.

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.

The section then documents how reachability is defined.

In particular, the relevant points in your case are:

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

A break, continue, return, or throw statement cannot complete normally.

So your "line 1" statement is preceded by a statement (break;) which cannot complete normally, and therefore it's unreachable.