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.
1. What is the problem with IF statement? Explanation: The IF statement has a priority according to which conditions are being tested. Whenever it is found to be true, all the following ELSIF statements are skipped and the END IF is executed.
When the condition after if is true, only the first block is executed. The else block is only executed when the condition is false.
The if statement is skipped because you have a bug and you don't yet fully understand what you're doing. That's normal for a newbie. Learn how to debug by using your IDE's facilities and using println statements. You'll get it if you work at it.
If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear". length < 3); if ("Jon".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With