The core reason Java doesn't detect all unreachable statements is that it's generally impossible to answer whether the code is reachable or not. This follows from the fact that halting problem is undecidable over Turing machines.
So, it's clear that all unreachable statements cannot be detected, but why not to try evaluating conditions? Imagine now that the condition used is not just false
but something like ~x == x
. For example, all these statements will print true
for every int x
(source).
System.out.println((x + x & 1) == 0);
System.out.println((x + -x & 1) == 0);
System.out.println((-x & 1) == (x & 1));
System.out.println(((-x ^ x) & 1) == 0);
System.out.println((x * 0x80 & 0x56) == 0);
System.out.println((x << 1 ^ 0x1765) != 0);
The statements can be rather complicated; it takes time to resolve them. It would significantly increase build time, and after all, it will not detect all unreachable statements. Compiler was designed to take some efforts but not spend too much time for that.
The only question remained is: where to stop resolving conditions? The reasons for that don't seem to have mathematical justification and are based on usage scenario. Rationale for your particular case is given by JLS-14.21
continue
is not going to exit anything... – VaduzA break, continue, return, or throw statement cannot complete normally.
. Even with return it produces an error. – Houseworkcontinue
is reachable, there's no exit path from the loop. – Patella