如果if参数在java中已经设置为true,那么为什么if的情况不会产生任何错误

Vis*_*uth 0 java compiler-errors compilation

当if参数为true时,为什么java程序在if else情况下不会出错.为什么不做任何例外.例如,这里method1和method2即使有无法访问的语句也不会产生任何(编译)错误,但是method3会产生编译错误.首先仔细阅读代码并提供答案.

    public int method1() {
        if(true) {
            return 1;
        } else {
            return 2;//unreachable statement but doesn't make exception
        }
    }

    public int method2() {
        if(true) {
            return 1;//unreachable statement but doesn't make exception
        } else if (true) {
           return 2;//unreachable statement but doesn't make exception
        } else {
            return 3;//unreachable statement but doesn't make exception
        }
    }

    public int method3() {

        if(true) {
            return 1;//unreachable statement but doesn't make exception
        } else if (true) {
           return 2;//unreachable statement but doesn't make exception
        } else {
            return 3;//unreachable statement but doesn't make exception
        }

        return 3;//unreachable statement but makes exception
    }
Run Code Online (Sandbox Code Playgroud)

java不支持严格的编译吗?这个问题背后的原理是什么?

And*_*mas 6

该语言允许通过为if-then-else创建一个特殊情况来进行条件编译.这样可以在编译时轻松打开或关闭代码块.

Java语言规范的无法访问语句部分:

   As an example, the following statement results in a compile-time error:

          while (false) { x=3; }

   because the statement x=3; is not reachable; but the superficially similar case:

          if (false) { x=3; }

   does not result in a compile-time error. 
Run Code Online (Sandbox Code Playgroud)

和:

   The rationale for this differing treatment is to allow programmers to 
   define "flag variables" such as:

          static final boolean DEBUG = false;

   and then write code such as:

          if (DEBUG) { x=3; }

   The idea is that it should be possible to change the value of DEBUG 
   from false to true or from true to false and then compile the code 
   correctly with no other changes to the program text.
Run Code Online (Sandbox Code Playgroud)