Search code examples
javaandroidandroid-studiojavac

Why does compiler build return unreachable code in some cases


If I write

private void check(){
   if(true)
      return;

   String a = "test";
}

Above code works normally, but if I write

private void check(){
   return;

   String a = "test";
}

The compiler/gradle in Android studio doesn't let this one through even though it's the same, and it says that the code after return in example 2 is unreachable.

I don't have any issues regarding this but I am eager to know why?


Solution

  • This is explained by the Unreachable Statements part of the Java Language Specification.

    There are quite a few rules, with an interesting special case. This is a compile time error :

    while (false) {
        // this code is unreachable
        String something = "";
    }
    

    while this is not :

    if (false) {
        // this code is considered as reachable
        String something = "";
    }
    

    The given reason is to allow some kind of conditional compilation, like :

    static final boolean DEBUG = false;
    ...
    if (DEBUG) { x=3; }
    

    So in your case :

    private void check(){
        if(true)
            return;
    
        // NO compilation error
        // this is conditional code
        // and may be omitted by the compiler
        String a = "test";
    }
    

    is not an error because of the special if treatment, using while instead is not accepted :

    private void check(){
        while(true)
            return;
    
        // "Unreachable statement" compilation error
        String a = "test";
    }
    

    This is also en error :

    private void check(){
        if(true)
            return;
        else
            return;
    
        // "Unreachable statement" compilation error
        String a = "test";
    }