Search code examples
javaif-statementcompiler-constructionlanguage-lawyer

(Compiler) else if(true) vs else scenario


Take the following Java code snippet:

....
    else if (true){ //hard-coded as true
     ///launch methodA
    }
    else {
     ///launch methodA (same code as in the ` else if ` statement)
    }
....

What I was wondering is how the compiler deals with this. Wouldn't it be logical for the compiler to remove the else if(true) statement altogether in order to not have to perform a check, even though it is hard-coded as true. Specifically in Eclipse, how is the code above interpreted?

Or what about in the following scenario:

....
    else if (true){ //hard-coded as true
     ///launch methodA
    }
    else {
     ///launch methodBB
    }
....

Wouldn't it be logical in this case for the compiler to remove the else statement? Because while running, the else statement is unreachable.


Solution

  • Unreachable statements are forbidden in Java and must trigger compilation errors. The JLS defines what is an unreachable statements: https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21

    It is too long to be entirely quoted here, but here is an extract (emphasis mine):

    if (false) { x=3; }
    

    does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

    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.

    So the answer will depend on the compiler you use and its optimization options.