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.
In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as: public static String checkNumber( int number) { //initialize variable i.
Code Inspection: Missing return statement The foo function must return the integer value but the function body returns nothing. To fix the error, add a RETURN statement (for example, return 1; ).
The missing return statement error is a compile-time error. Therefore this type of error tends to be easy to detect. The main causes are: a return statement was simply omitted by mistake. the method doesn't return any value, but type void is not declared in the method signature.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
JLS 14.21, Unreachable Statements is the section that deals with this:
The if statement, whether or not it has an else part, is handled in an unusual manner. For this reason, it is discussed separately at the end of this section.
Ultimately it has to do with how conditional compilation is handled. Consider this method:
public int foo() { if (DEBUG) { return 5; } }
If DEBUG
is static final boolean true;
you might think the compiler should be smart enough to realize the method will always return 5
. But if it's changed to false
, 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.
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