Search code examples
javaeclipseif-statementcompiler-warningsfinal

Java compiler/eclipse not reconizing dead code


So I recently came accros this. I was creating an if-else-statement with as it's condition a final boolean variable. Eclipse immediatly told me that the else part of the code was unreachable and therefore dead code. This was my code(compacted).

public static void main(String[] args){
    final boolean state = true;
    if(state == true){
        System.out.println("A");
    }else{
        System.out.println("B");
    }
}

Then I though what would happen if the code stayed the same but the variable wasn't final anymore? So I tried that and this was what happened, nothing no warnings or errors. The code:

public static void main(String[] args){
    boolean state = true;
    if(state == true){
        System.out.println("A");
    }else{
        System.out.println("B");
    }
}

Now I'm wondering, why is the first case detected and flagged and the second case not?

Thank you in advance.


Solution

  • Try this as an alternative.

    public class Test061 {
        public static void main(String[] args){
            int a = 0;
            if(1 == (a+1)){
                System.out.println("A");
            }else{
                System.out.println("B");
            }
        }
    }
    

    There are still no warnings. Why?

    Because the compiler does not execute your code. It only can issue a warning when it sees some "constants" or "constant expressions". Apparently when you put final the compiler then knows that this value cannot change. While if you use "real variables" or "variable expressions", it doesn't know because it doesn't execute your code (to see what the value of state or (a+1) is at this line). So in the latter case, you get no warnings. Hope this makes more sense now.

    Think of it this way: the compiler does some code analysis. The first basic pattern is detected by this analysis, while the second pattern is not (probably as it's not that basic).