I have a question regarding return statements used within if()
while()
or for()
statements.
As you can see in the following method, it is expecting that I return
a String value.
The problem is that if I were to use a return
statement within my if
statement block, the compiler would return the error missing return statement
.
public String myMethod()
{
if(condition)
{
return x;
}
}
Of course I could change the method header to void
and use System.out.println
instead of return
. But is this the right way to do it? am i missing something?
Any help is highly appreciated.
You have to add a return statement if the
condition
is false.FYI:
Oracle docs for return statement
If you put return statement in
if
,while
orfor
statement then it may or may not return value. If it will not go inside these statement 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 afterif
,while
orfor
.But if you write
if
/else
block and each one of them is having return in it then compiler knows that eitherif
orelse
will get execute and method will return a value. So this time compiler will not force you.Any how myMethod() should return a String value .what if your condition is false is myMethod return anything? ans is no so you need to define return null or some string value in false condition