If you put a return statement in the if, while or for statement then it may or may not return a value. If it will not go inside these statements then also that method should return some value (that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.
But if you write an if / else block and each one of them is having a return in it then the compiler knows that either the if or else will get executed and the method will return a value. So this time the compiler will not force you.
if(condition)
{
return;
}
else
{
return;
}
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 return? 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 this to solve your problem:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}