“Missing return statement” within if / for / while

2018-12-31 07:26发布

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.

标签: java return
10条回答
倾城一夜雪
2楼-- · 2018-12-31 08:16

You have to add a return statement if the condition is false.

public String myMethod() {
    if(condition) {
        return x;
    }

//  if condition is false you HAVE TO return a string
//  you could return a string, a empty string or null
    return otherCondition;  
}

FYI:

Oracle docs for return statement

查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 08:17

If you put return statement in if, while or for 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 after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}
查看更多
何处买醉
4楼-- · 2018-12-31 08:18
public String myMethod() // it ALWAYS expects a String to be returned
{
    if(condition) // will not execute always. Will execute only when condition is true
    {
       return x; // will not be returned always.
    }
   //return empty string here

}
查看更多
看风景的人
5楼-- · 2018-12-31 08:19

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

public String myMethod() {
    boolean c=true;
    if (conditions) {
        return "d";
    }
    return null;//or some other string value
}
查看更多
登录 后发表回答