In the following method, the compiler complains about a missing return statement even though there is only a single path through the method, and it contains a return statement. Suppressing the error requires another return statement.
public int foo() {
if (true) {
return 5;
}
}
Given that the Java compiler can recognize infinite loops, why doesn’t it handle this situation as well? The linked question hints, but doesn’t provide details for this specific case.
JLS 14.21, Unreachable Statements is the section that deals with this:
Ultimately it has to do with how conditional compilation is handled. Consider this method:
If
DEBUGisstatic final boolean true;you might think the compiler should be smart enough to realize the method will always return5. But if it’s changed tofalse, the code is no longer valid.The method must be valid for all paths through the method without a source code change, allowing optimizing compilers to omit bytecode without source modifications regardless of the flag’s value.
The very end of the linked JLS section goes in to significant detail.