Possible Duplicate:
Compiler complains about “missing return statement” even though it is impossible to reach condition where return statement would be missing
The following method in Java compiles fine.
public String temp() {
while(true) {
if(true) {
// Do something.
}
}
}
The method has an explicit return type which is java.lang.String with no return statement though it compiles fine. The following method however fails to compile.
public String tempNew() {
if(true) {
return "someString";
}
}
A compile-time error is issued indicating “missing return statement” even though the condition specified with the if statement is always true (it has a boolean constant that is never going to be changed neither by reflection). The method must be modified something like the following for its successful compilation.
public String tempNew() {
if(true) {
return "someString";
} else {
return "someString";
}
}
or
public String tempNew() {
if(true) {
return "someString";
}
return "someString";
}
Regarding the first case with the while loop, the second case appears to be legal though it fails to compile.
Is there a reason in the second case beyond one of the compiler’s features.
Because it is dead code. The dead code analysis is done in a separate pass to the method return analysis, which does some more in-depth analysis that looks inside branch conditions.