为什么编译器构建在某些情况下返回无法访问的代码

Tom*_*mek 7 java android javac android-studio

如果我写

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

   String a = "test";
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,但如果我写

private void check(){
   return;

   String a = "test";
}
Run Code Online (Sandbox Code Playgroud)

Android Studio中的编译器/ gradle虽然它是相同的,但它不会让这个通过,并且它表示在示例2中返回后的代码无法访问.

我对此没有任何问题,但我很想知道为什么?

bwt*_*bwt 1

Java 语言规范的不可到达语句部分对此进行了解释。

有很多规则,还有一个有趣的特殊情况。这是一个编译时错误:

while (false) {
    // this code is unreachable
    String something = "";
}
Run Code Online (Sandbox Code Playgroud)

虽然这不是:

if (false) {
    // this code is considered as reachable
    String something = "";
}
Run Code Online (Sandbox Code Playgroud)

给出的原因是允许某种条件编译,例如:

static final boolean DEBUG = false;
...
if (DEBUG) { x=3; }
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下:

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

    // NO compilation error
    // this is conditional code
    // and may be omitted by the compiler
    String a = "test";
}
Run Code Online (Sandbox Code Playgroud)

由于特殊处理,这不是错误,不接受if使用替代:while

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

    // "Unreachable statement" compilation error
    String a = "test";
}
Run Code Online (Sandbox Code Playgroud)

这也是一个错误:

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

    // "Unreachable statement" compilation error
    String a = "test";
}
Run Code Online (Sandbox Code Playgroud)