1

Can anyone help me to understand why java compiler not giving any error for code 1. As in code 1, there is no chance of executing line 2 at run-time. is compiler not validating if condition ? And why it is giving error on code 2.

Code 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 "";
         }
     }
}

Code 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
     }
     
}
pathe.kiran
  • 2,444
  • 1
  • 21
  • 27
  • 1
    code2 is rather obvious: nothing after the return statement can be executed. For code1 i would guess that the compiler is not evaluating the condition, even if it could easily be done for a constant value like that – f1sh Jun 17 '21 at 11:01
  • [Google search strategy used to find similar questions](https://www.google.com/search?q=java+if+else+does+not+cause+unreachable+statement+site:stackoverflow.com) – Hovercraft Full Of Eels Jun 17 '21 at 11:06

0 Answers0