I have a question regarding return statements used within if()
while()
or for()
statements.
As you can see in the following method, it
That's because the function needs to return a value. Imagine what happens if you execute myMethod()
and it doesn't go into if(condition)
what would your function returns? The compiler needs to know what to return in every possible execution of your function
Checking Java documentation:
Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.
This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).
You can do to solve your problem:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}