The main reason Java does not detect all unreachable statements is because it is generally impossible to answer whether the code is available or not. This follows from the fact that the stopping problem is unsolvable over Turing machines.
So, it is clear that all unattainable statements cannot be discovered, but why not try to evaluate the conditions? Imagine that the condition used is not just false , but something like ~x == x . For example, all of these operators will print true for each 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);
Operations can be quite complicated; it takes time to solve them. This will significantly increase the build time, and in the end, it will not detect all unreachable statements. The compiler was designed to make some effort, but not spend too much time on it.
The only question remains: where to stop allowing conditions? The reasons for this have no mathematical justification and are based on use cases. The rationale for your specific case is given by JLS-14.21
Sergey Fedorov Dec 30 '15 at 9:21 2015-12-30 09:21
source share