0

In testOne:

  • Why is the "else if" not unreachable (aNumber is final so the compiler should know it can't get past the "if" part, but it only gives a warning)?
  • Since "else if" apparently is reachable, why then is the "else" part not unreachable ("else if" is always true)?

In testTwo:

  • The "if (true)" is unreachable.

Is all this because the compiler somehow thinks my variable and boolean can change even if they are final("aNumber") and hardcoded("true"). And when there is no variable or boolean (the first "else" in testTwo) nothing can change, and since it mops up all possibilities by just saying "else" it knows it cant reach anything further down?

public int testOne() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else if (true) {
            return 2;
        } else {
            return 3;
        }
    }

public int testTwo() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else {
            return 1;
        }
        if (true) {
            return 3;
        } else {
            return 4;
        }
    }
Oyst
  • 1
  • 4
  • The compiler does a static analysis to emit warnings. Compiler does not know what the variable value is , but it does know the flow of logic. So , in case 1 it does not emit a warning, as value 5 is known only at run time. In case 2, there is an if/else present and in both case you return, so compiler knew the return will work either way and it will not reach the if below.! – Kris Jun 23 '22 at 14:44
  • Aha, and even if I make "aNumber" static (and place it outside the method to make it work), the compiler still doesn't know the value? (It gives the same result at least). – Oyst Jun 23 '22 at 15:09
  • Btw, the compiler does give a warning in case 1 (as stated in the first question), and it must know the value on some level since the warning is that the first "if" is always true... It's still not clear to me sry:) – Oyst Jun 23 '22 at 16:00

0 Answers0