javaif-statementcompiler-errorsconditional-statements

Does the java compiler understand conditions given in if statements?


The following code does not give the compile-error Unreachable statement.

if(true)return;
int x;

For years I believed that it's because the compiler does not pay much attention to the conditions given.

Today I found that the compiler understands the conditions,

int x;
if (true) {
    x = 0;
}
int y = x;

because if not this should result in another compile-error variable x might not have been initialized. Which in fact compiles and runs perfectly. So,

Does the java compiler understand conditions given in if statements?


Solution

  • Unreachable Statements is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

    For example, a Java compiler will accept the code:

    int n = 5;
    while (n > 7) k = 2;
    

    even though the value of n is known at compile time and in principle it can be known at compile time that the assignment to k can never be executed.

    The rules in this section define two technical terms:

    The definitions here allow a statement to complete normally only if it is reachable.

    To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."


    Source :