当我们在 if 块中使用 return 语句时,为什么编译器没有给出任何错误?

时间:2021-06-17 10:53:29

标签: java

谁能帮我理解为什么 java 编译器没有给出代码 1 的任何错误。在代码 1 中,没有机会在运行时执行第 2 行。编译器不验证 if 条件吗? 以及为什么它在代码 2 上出错。

代码 1:

public class HelloWorld{

     public static void main(String []args){
        m1();
     }
     
     public static String m1() {
         if(true){
             System.out.println("if");
             return ""; //line 1
         } else {
             System.out.println("else"); // line 2
             return "";
         }
     }
}

代码 2:

public class HelloWorld{

     public static void main(String []args){
        m1();
     }
     
     public static String m1() {
         return "";
         System.out.println("last statement"); //compile error : unreachable statement
     }
     
}

0 个答案:

没有答案
相关问题